Home > Software design >  Get 2 words within a string using PHP
Get 2 words within a string using PHP

Time:09-22

I am trying to get 2 words from a string, where the 2 words can be different each time.

In this example, I'm trying to get Open and On Hold

$str = 'Status Changed from Open to On Hold';

I've managed to get Open with this code:

$starting_word = 'Status Changed from';
$ending_word = 'to';

$subtring_start = strpos($str, $starting_word).strlen($starting_word);
$size = strpos($str, $ending_word, $subtring_start) - $subtring_start; 
$a = substr($str, $subtring_start, $size);

And then I tried to get On Hold using this, but it's returning nothing.

$subtring_start = strpos($str, $a);
$size = strpos($str, '', $subtring_start) - $subtring_start;
$b = substr($str, $subtring_start, $size);
echo $b;

CodePudding user response:

You'll get some good answers on how to do it similar to your approach, but this is easier:

preg_match('/ from ([^ ] ) to (.*)/', $str, $matches);
echo $matches[1];
echo $matches[2];
  • match a space and from and a space
  • capture () anything not a space [^ ] up to a space and to
  • capture () anything .* to the end

CodePudding user response:

Even though you haven't made clear what the specific dynamic words are, but you can try the following code to get the second string, that is, in your case, 'On Hold'.

$str = 'Status Changed from Open to On Hold';

$starting_word = 'Status Changed from';
$ending_word = 'to';

$size = strpos($str, $ending_word);
$second_value = substr($str, $size 3);
echo $second_value;

Output:

On Hold

Try and change the 'On Hold' in your $str and run the code again, and see the magic.

Try it online!

  •  Tags:  
  • php
  • Related