首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何删除带有特殊字符的字符串的结尾?

如何删除带有特殊字符的字符串的结尾?
EN

Stack Overflow用户
提问于 2016-08-12 05:51:01
回答 3查看 134关注 0票数 1

我的绳子就像

代码语言:javascript
复制
Clothing, Shoes & Accessories:Men's Clothing:T-Shirts

我想去掉像T恤一样的绳子末端。结果应该是

代码语言:javascript
复制
Clothing, Shoes & Accessories:Men's Clothing

我在用

代码语言:javascript
复制
end(explode(':',"Clothing, Shoes & Accessories:Men's Clothing:T-Shirts"));

但我只买T恤衫

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-08-12 05:57:05

您可以使用简单的正则表达式:

代码语言:javascript
复制
<?php
$string = "Clothing, Shoes & Accessories:Men's Clothing:T-Shirts";
$regex = '~:[^:]*$~';
$string = preg_replace($regex, '', $string);
echo $string;
# Clothing, Shoes & Accessories:Men's Clothing   
?>
票数 2
EN

Stack Overflow用户

发布于 2016-08-12 05:55:37

正如您所提到的,在爆炸之后,您需要删除最后一个数组元素。这就是pop()函数派上用场的地方。

它将删除最后一个元素。然后再试一步,将数组内爆。

试试这个:

代码语言:javascript
复制
$arr = explode(':', $string);
array_pop($arr);
echo implode(':', $arr);  // Clothing, Shoes & Accessories:Men's Clothing
票数 2
EN

Stack Overflow用户

发布于 2016-08-12 06:13:29

好的,所以your ()函数按预期工作,并将字符串拆分成一组较短的字符串,并将它们填充到一个数组中。

函数返回数组的最后一个元素,这就是为什么只看到最后一个文本部分的结果。你真正想做的是把每个部分都拿回来,除了最后一个,对吗?

可以通过将数组重新组合回字符串来做到这一点,但如果您想继续沿着您似乎在上面的路径前进,但是没有它的最终成员,则可以这样做:

代码语言:javascript
复制
// 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);

搜索分隔符的最后一次出现并从那里删除字符串中的任何字符可能会更容易,但我不确定这是否符合用例。为了完整起见,您可能会这样做:

代码语言:javascript
复制
// 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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38910817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档