-1

I'm using regex to find a word or some words in a string. For example:

if(preg_match("~\bbet\b~",$text) !== false)  // want to find "bet" in string

Mean i want to check if it there is bet in that string ($text)

But, if $text = "there is difference between this string and that string", it will return true.

Now, i want, for example these will return true:

$text = "I bet he's a virgin!"

$text = "Bet you're glad you flew out there."

But this sentence will return false

$text = "there is difference between this string and that string"

Or 1 more example for harder string:

I want to find "hi" in string But not hi in this

It will return true if

$text = "hi";

But return false if

$text = "this";

Jasmine
  • 1
  • 1
  • There is no match [here](https://regex101.com/r/5TufES/1), in `there is difference between this string and that string`. `\bbet\b` only searches for `bet` as a whole word. Use `"~\bbet\b~i"` to make the search case insensitive. – Wiktor Stribiżew Jun 16 '19 at 16:54
  • Duplicate of [PHP preg_match to find whole words](https://stackoverflow.com/questions/4722007/php-preg-match-to-find-whole-words) – Wiktor Stribiżew Jun 16 '19 at 18:51
  • Also a dupe of [Regex: ignore case sensitivity](https://stackoverflow.com/questions/9655164/regex-ignore-case-sensitivity) – Wiktor Stribiżew Jun 16 '19 at 18:54

1 Answers1

0

For bet to return true, we can use a lookahead with word boundary and i flag, with an expression similar to:

.*(?=\bbet\b).*

Demo 1

$re = '/.*(?=\bbet\b).*/mi';
$str = 'I bet he\'s a virgin!
Bet you\'re glad you flew out there.
I betty he\'s a virgin!
Betty you\'re glad you flew out there.';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);

We can similarly check for hi and this:

.*(?=\bhi\b).*

Demo 2

TEST 2

$re = '/.*(?=\bhi\b).*/mi';
$str = 'there is difference between this string and that string
hi there, is difference between that string and other string false?

';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Emma
  • 27,428
  • 11
  • 44
  • 69