Reputation: 31
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
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
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
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
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