jaffamoney
jaffamoney

Reputation: 31

Search two words in string to verify that one word precedes the other word

After a lot of googling, asking question on here. I want to be able to search a string to verify that one word precedes the other (in php), but not necessarily adjacent to each other. I was so sure it would be simple, but struggled to find an answer!

Upvotes: 0

Views: 110

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89566

You can try this:

if (preg_match('~^(?>[^bg]+|\B[bg]|b(?!adword\b)|g(?!oodword))*+\bgoodword\b~', $str, $match))
    echo 'ok';
else
    echo 'fail';

you must take the first letter of "badword" ("b") and allows it only if it is not followed by "adword"

^ is an anchor for the start of the string

\b is a word boundary and \B is the opposite.

(?!...) means "not followed by"

An example with some text stored into variable :$text_before, $text_after

$flb = preg_quote($text_before[0]);
$fla = preg_quote($text_after[0]);
$subb = substr($text_before, 1);
$suba = substr($text_after, 1);

if( preg_match('~^(?>[^' . $flb . $fla . ']+|\B[' . $flb . $fla ']|'
             . $flb . '(?!\Q' . $subb . '\E\b)|'
             . $fla . '(?!\Q' . $suba . '\E\b))*+\b'
             . $text_after . '\b~', $str, $match) ) {
    echo 'ok';
} else {
    echo 'fail';
}

Upvotes: 0

ilpaijin
ilpaijin

Reputation: 3695

At first I thought to suggest you to use strpos(), but maybe it can't work if you need to match the exact words. I'm investigating on something like this:

function AbeforeBinC($a, $b, $string)
{
    $aStr = explode(' ', strtolower($string));
    foreach($aStr AS $k => $s)
    {
    if($a == $s){ $a = $k; }
    if($b == $s){ $b = $k; }
    }
    var_dump($a < $b);
}

$str = "We are here to take care of you";

AbeforeBinC('are', 'take', $str);

Upvotes: 0

user557597
user557597

Reputation:

Maybe this

 #  ^(?:(?!word_after).)*word_before(?:(?!word_after|word_before).)*word_after(?:(?!word_before).)*$

 ^ 
 (?:
      (?! word_after )
      . 
 )*

 word_before 

 (?:
      (?! word_after | word_before )
      . 
 )*

 word_after

 (?:
      (?! word_before )
      . 
 )*
 $ 

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

If that is the only requirement, then maybe:

if(($pos = strpos($haystack, $first_word)) !== false && strpos($haystack, $second_word, $pos)) {
    // $second_word found after $first_word
}

Upvotes: 1

Related Questions