how do I get everything in a php string before and after a certain word? For example, if I have a string that says "5 times 8", how do I extract the 5 and the 8 and store them into separate variables? I'm kinda new to PHP.
I've tried
$foo = "5 times 8";
$foo = str_replace(" times ","",$foo);
Then what? The result is "58"
If you are certain that your input string contains " times "
then you can do this:
$input = "5 times 8";
list($a, $b) = explode(' times ', $input);
echo $a; // "5"
echo $b; // "8"
If you need to do something a little more complex, use regular expressions:
$input = "5 times 8";
if (preg_match('!(\d+)\s*times\s*(\d+)!i', $input, $m)){
$a = $m[1];
$b = $m[2];
}
You can use the explode() function, like this:
$string = "5 times 8";
$var = explode(' times ', $string);
echo $var[0]; //echoes 5
echo $var[1]; //echoes 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With