簡體   English   中英

找到-時刪除php中的單詞-

[英]Remove words in php when finding a -

我有下面的代碼在哪里切詞。 如果在單詞前面找到一個-我剪切了單詞,只剩下第一部分

<?php

    $values = array("PANELEGP00001",
    "PANELEGP00003",
    "PANELEGP00001-1",
    "PANELEGP00002-TOS",
    "PANELEGP00004-2",
    "LIVOR-44_900_2100",
    "004-00308D" 
  );

  foreach ($values as $i => &$value) {
      $words = explode("-", $value);      
        if (preg_match("/[a-z]/i", $words[1])) {       
          $value = $words[0];
      }
  }

    PANELEGP00001
    PANELEGP00003
    PANELEGP00001-1
    PANELEGP00002   //I REMOVE THE WORD TOS
    PANELEGP00004-2
    LIVOR-44_900_2100
    004             // This should not be cut, it because there is a letter
               at the end. I want to cut only if I find a letter at the beginning

?>

我想只有當我覺得在這樣的開頭字母削減PANELEGP00002-TOS但不是在這一個004-00308D或這一個004-0D3080只有前面一個字母-

這有效,只需測試第二部分的第一個字母是否為數字:

$values = array(
    "PANELEGP00001",
    "PANELEGP00003",
    "PANELEGP00001-1",
    "PANELEGP00002-TOS",
    "PANELEGP00004-2",
    "LIVOR-44_900_2100",
    "004-00308D" 
);

foreach ($values as $i => &$value) {
    $words = explode('-', $value);

    // test if word contains "-"
    if (count($words) > 0) {
        // test first char of second part
        if (! is_numeric($words[1][0])) {
            // if first char is a letter, just keep first part
            $values[$i] = $words[0];
        }
    }
}

// $values contains correct rows
var_dump($values);

基於ctype_alpha()。

  $values = array("PANELEGP00001",
                  "PANELEGP00003",
                  "PANELEGP00001-1",
                  "PANELEGP00002-TOS",
                  "PANELEGP00004-2",
                  "LIVOR-44_900_2100",
                  "004-00308D" );

  foreach ($values as $i => &$value) {
    if(ctype_alpha(substr($value,0,1))){
      if(strpos($value,'-')){
         $value = substr($value,0,(strpos($value, '-' )));
      }
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM