Clothing, Shoes & Accessories:Men's Clothing:T-Shirts
我想删除像T恤字符串的结尾。 而且结果应该是
Clothing, Shoes & Accessories:Men's Clothing
我使用
end(explode(':',"Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"));
但我只得到T恤
感谢
Clothing, Shoes & Accessories:Men's Clothing:T-Shirts
我想删除像T恤字符串的结尾。 而且结果应该是
Clothing, Shoes & Accessories:Men's Clothing
我使用
end(explode(':',"Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"));
但我只得到T恤
感谢
您可以使用一个简单的正则表达式:
<?php
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts";
$regex = '~:[^:]*$~';
$string = preg_replace($regex, '', $string);
echo $string;
# Clothing, Shoes & Accessories:Men's Clothing
?>
从你所提到的东西,看起来像爆炸后,你需要删除最后一个数组元素。这是array_pop()函数派上用场的地方。
它将删除最后一个元素。然后再尝试一步,并使阵列爆裂。
试试这个:
$arr = explode(':', $string);
array_pop($arr);
echo implode(':', $arr); // Clothing, Shoes & Accessories:Men's Clothing
好了,你的爆炸()函数工作正常,并分裂串入一组短字符串并将它们填充到数组中。
end()函数返回数组的最后一个元素,这就是为什么您只能看到最后一个文本部分的结果。你真正想要做的是得到的每一部分,除了最后一个回来,对吧?
您可以通过重新组合排列回字符串,如果你想保持下去的路径,你似乎是在做,但没有它的最后一个成员,:
// Set the string with initial content
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts";
// Explode the string into an array with 3 elements
$testArray = explode(':', $string);
// Make a new array from the old one, leaving off the last element
$slicedArray = array_slice($testArray, 0, -1);
// Implode the array back down to a string
$newString = implode(':', $slicedArray);
它可能会更容易搜索分隔符的最后一次出现并从中删除字符串中的任何字符,但我不确定这是否适合您的用例。为了完整性,你可能会这样做:
// Set string with content
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts";
// Get index of last : character in the string
$lastIndex = strrpos($string, ':');
// Set new string to left portion of original string up til last : char
$newString = substr($string, 0, $lastIndex);
你到底想要保留什么?服装或T恤衫的一部分? – Jan