I've got a string which goes something like myString__sfsdfsf
All I know is that there is a __
somewhere in the string. Content of the string and number of characters is unknown.
I want to remove the __
and all characters that follow so I am left with just myString
. How can I achieve this using PHP?
This can be done in several ways. PHP has lots of string functions. You can pick one depending on your requirements. Here are some ways:
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__')); // => myString
Or use strtok()
:
echo strtok($str, '__'); // => myString
Or, maybe even explode()
:
echo explode('__', $str)[0]; // => myString
You can make use of strpos() and substr():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__'));
This should be quite fast. However if you need something more fancy than that, you probably want to look into regular expressions, e.g. preg_match().
list($string,) = explode('_', 'myString__sfsdfsf');
echo $string; // Outputs: myString
A str_replace() would also work$string = str_replace('__', '', $string);
Ignore that, didn't read your question properly