0

当它们等于时,如何修剪最后三个字符"01x"

例如,我有这个:

$stuff = array(
    "aaaaa01x",
    "aaaaa1",
    "aaaaa01x",
    "aaaaa01",
    "aaaaa01",
    "aaaaa01x"
    "aaaaa11"
);

我正在尝试输出:

$stuff = array(
    "aaaaa", // trimmed
    "aaaaa1",
    "aaaaa", // trimmed
    "aaaaa01",
    "aaaaa01",
    "aaaaa", // trimmed
    "aaaaa11"
);

我尝试使用 执行此操作时遇到问题trim(),因为trim()修剪掉任何以三个字符中的任何一个字符结尾的字符串。

例如,将从任何以这些字符结尾的字符串中trim($string, '01x');剪掉"1", 。我只想在字符串以“01x”结尾时进行修剪。"0""x"

4

4 回答 4

2
$stuff = array(
    "aaaaa01x",
    "aaaaa1",
    "aaaaa01x",
    "aaaaa01",
    "aaaaa01",
    "aaaaa01x",
    "aaaaa11"
);

for($i = 0; $i < count($stuff); $i ++)
{
    $stuff[$i] = (substr($stuff[$i], -3) == '01x' ? substr($stuff[$i], 0, -3) : $stuff[$i]);    
}
于 2013-09-02T23:11:15.073 回答
1

代码:

$stuff = array(
    "aaaaa01x",
    "aaaaa1",
    "aaaaa01x",
    "aaaaa01",
    "aaaaa01",
    "aaaaa01x",
    "aaaaa11"
);

foreach($stuff as $key => $thing) {
   if(substr($thing, -3, 3) == '01x')
      $stuff[$key] = trim($thing, '01x');
}

var_dump($stuff);

输出:

array(7) {
   [0]=> string(5) "aaaaa"
   [1]=> string(6) "aaaaa1"
   [2]=> string(5) "aaaaa"
   [3]=> string(7) "aaaaa01"
   [4]=> string(7) "aaaaa01"
   [5]=> string(5) "aaaaa"
   [6]=> string(7) "aaaaa11"
}
于 2013-09-02T23:11:42.090 回答
1

通过循环运行数组,并创建一个新数组。

$i = 0;
foreach($stuff as $s){
$stuff[$i] = preg_replace('/01x$/', '', $s);
$i++;
}
于 2013-09-02T23:14:53.910 回答
0

您可以使用strrpos()来查找搜索字符串的最后一个位置。

$stuff = array(
    "aaaaa01x",
    "aaaaa1",
    "aaaaa01x",
    "aaaaa01",
    "aaaaa01",
    "aaaaa01x",
    "aaaaa11"
);

for ($i = 0; $i < count($stuff); $i++) {
    if (($pos = strrpos($stuff[$i], '01x')) !== FALSE) {
        $stuff[$i] = substr($stuff[$i], 0, $pos);
    }
}

print_r($stuff);
于 2013-09-02T23:29:40.797 回答