简体   繁体   中英

How to find a substring from a string using regular expression in php?

I have a string like "I love my country". If i search for 'country' my program will show "exist". But if I search 'count' my program will show "Not exist".

Is this what you're looking for?

I'm not a master of Regex so someone may have a more optimal solution but simply searching for country with word boundaries should get you what you're after.

/\\b(country)\\b/g

So in PHP something like the following:

$string = 'I love my country';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: Match Found

And one that fails:

$string = 'I love mycountry';
$matchExists = preg_match('/\b(country)\b/', $string);

echo ($matchExists) ? 'Match Found' : 'No Match Found'; // Output: No Match Found

And reminder you can see a bunch of different outputs here as well as test any others you may have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM