我的绳子就像
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恤衫
谢谢
发布于 2016-08-12 05:57:05
您可以使用简单的正则表达式:
<?php
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts";
$regex = '~:[^:]*$~';
$string = preg_replace($regex, '', $string);
echo $string;
# Clothing, Shoes & Accessories:Men's Clothing
?>发布于 2016-08-12 05:55:37
正如您所提到的,在爆炸之后,您需要删除最后一个数组元素。这就是pop()函数派上用场的地方。
它将删除最后一个元素。然后再试一步,将数组内爆。
试试这个:
$arr = explode(':', $string);
array_pop($arr);
echo implode(':', $arr); // Clothing, Shoes & Accessories:Men's Clothing发布于 2016-08-12 06:13:29
好的,所以your ()函数按预期工作,并将字符串拆分成一组较短的字符串,并将它们填充到一个数组中。
函数返回数组的最后一个元素,这就是为什么只看到最后一个文本部分的结果。你真正想做的是把每个部分都拿回来,除了最后一个,对吗?
可以通过将数组重新组合回字符串来做到这一点,但如果您想继续沿着您似乎在上面的路径前进,但是没有它的最终成员,则可以这样做:
// 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);https://stackoverflow.com/questions/38910817
复制相似问题