Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get everything before and after a certain word in string [closed]

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"

like image 327
Thomas Lai Avatar asked Mar 25 '13 00:03

Thomas Lai


2 Answers

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];
}
like image 148
Cal Avatar answered Sep 20 '22 17:09

Cal


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
like image 38
Nelson Avatar answered Sep 20 '22 17:09

Nelson