I have a string, example:
32137hyb8bhbhu837218nhbuhuh&3298j19j2n39
I want to remove (clean) from the string everything that comes after &
.
Please, how to do this?
I have a string, example:
32137hyb8bhbhu837218nhbuhuh&3298j19j2n39
I want to remove (clean) from the string everything that comes after &
.
Please, how to do this?
You can use the explode function to do this.
$str = "32137hyb8bhbhu837218nhbuhuh&3298j19j2n39";
$str = explode("&",$str);
echo $str[0];
What is the way out
32137hyb8bhbhu837218nhbuhuh
The explode
function divides a string by the given separator and returns an array containing the separated parts.
Since it divides the string 32137hyb8bhbhu837218nhbuhuh&3298j19j2n39
into two parts 32137hyb8bhbhu837218nhbuhuh
and 3298j19j2n39
and stores each part in an array index. The part that you need can be accessed in the first array index, in this case, $str[0]
.
You can see it working online here
You can use strstr()
function by passing the third argument that returns only the left part of the delimiter:
echo strstr('32137hyb8bhbhu837218nhbuhuh&3298j19j2n39', '&', true);
Return:
32137hyb8bhbhu837218nhbuhuh
If you have a preference for REGEX
, which I find difficult, you could use this:
$string = '32137hyb8bhbhu837218nhbuhuh&3298j19j2n39';
preg_match('/(.*)&/', $string, $match);
echo $match[1];
Answer:
32137hyb8bhbhu837218nhbuhuh
preg_match
uses REGEX
of /(.*)&/
will get everything ( .*
) that is before &
.
By adding one more option, you can use the combination of % w / a> and substr
:
$text = '32137hyb8bhbhu837218nhbuhuh&3298j19j2n39';
echo substr($text, 0, strrpos($text, '&'));
Resulting in:
32137hyb8bhbhu837218nhbuhuh
Check out ideone