如果最后三个字符等于"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"
,"0"
,"x"
。我只想在字符串以“01x”结尾时修剪。
答案 0 :(得分: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]);
}
答案 1 :(得分: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"
}
答案 2 :(得分:1)
通过循环运行数组,并创建一个新数组。
$i = 0;
foreach($stuff as $s){
$stuff[$i] = preg_replace('/01x$/', '', $s);
$i++;
}
答案 3 :(得分: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);