我有以下代码用来切词。如果在单词前面找到-
,则将单词切掉,仅保留第一部分
<?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
中才找到字母时,才想剪切1}}
答案 0 :(得分:2)
这有效,只需测试第二部分的首字母是否为数字即可:
$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);
答案 1 :(得分:0)
基于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, '-' )));
}
}
}