tags:

views:

1711

answers:

2

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

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

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

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

+5  A: 

You could do this, using explode:

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

Or you could also do this, using substr and strpos:

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

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

Paolo Bergantino
You don't even need a $garbage variable: list($what_you_want, ) = explode('(', $str, 2); works as well.
htw
indeed it does. fixed.
Paolo Bergantino
Also, he said strstr($str, '(', true); doesn't work, so I assume he doesn't have 5.3.0…
htw
Whoops, never mind that last comment—I must not have noticed the edit.
htw
It's all good. Seems quite unlike PHP to allow that trailing comma in the list, I'm kinda shocked that works. Good to know, I guess.
Paolo Bergantino
+2  A: 
$a=substr($a, 0, strpos($a, '('));
Niran