php 用php在符号前剪切字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/780374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:49:38  来源:igfitidea点击:

Cut string before a symbol with php

php

提问by Jin Yong

How can I cut the string before '(' sign with php

如何在 '(' 用 php 符号之前剪切字符串

For example: $a = "abc dec g (gold)";

例如:$a = "abc dec g (gold)";

How can I cut the string become only "abc dec g"??

我怎样才能把字符串剪成只有“abc dec g”??

I tried to used this strstr($a, '(', true) but error display.

我尝试使用这个 strstr($a, '(', true) 但错误显示。

回答by Paolo Bergantino

You could do this, using explode:

你可以这样做,使用explode

list($what_you_want,) = explode('(', $str, 2);

Or you could also do this, using substrand strpos:

或者你也可以这样做,使用substrand strpos

$what_you_want = substr($str, 0, strpos($str, '('));

The reason you got the error using strstris because the last argument is not available unless you have PHP 5.3.0 or later.

使用时出现错误strstr的原因是最后一个参数不可用,除非您有 PHP 5.3.0 或更高版本。

回答by Niran

$a=substr($a, 0, strpos($a, '('));

回答by caktux

How about strstr:

strstr怎么样:

$topic = strstr('Some topic :: part to exclude', '::', TRUE);

$topic = strstr('Some topic :: part to exclude', '::', TRUE);

then

然后

$topic= Some topic

$topic= 一些话题

Edit: right... 5.3+ only

编辑:对...仅 5.3+

回答by Joan-Diego Rodriguez

Using this piece of code is indeed a good solution:

使用这段代码确实是一个很好的解决方案:

$what_you_want = substr($str, 0, strpos($str, '('));

Still, I would like to point to the fact that it will cut your string at the first occurence of "(". Shoud you want to cut it at the LAST occurence of "(", you should use

不过,我想指出这样一个事实,它会在第一次出现“(”时切断你的字符串。如果你想在最后一次出现“(”时切断它,你应该使用

$what_you_want = substr($str, 0, strrpos($str, '('));

I found it to be often the case when scrapping html content for example (because of nested tags).

例如,我发现在废弃 html 内容时经常出现这种情况(因为嵌套标签)。

Cheers, Joan

干杯,琼