Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut string before a symbol with php

Tags:

php

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.

like image 638
Jin Yong Avatar asked Apr 23 '09 04:04

Jin Yong


People also ask

How do I trim a string after a specific character in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do you get something before a certain character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.


2 Answers

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.

like image 123
Paolo Bergantino Avatar answered Oct 30 '22 09:10

Paolo Bergantino


$a=substr($a, 0, strpos($a, '('));
like image 32
Niran Avatar answered Oct 30 '22 11:10

Niran