How to Find a Whole Word in a String in PHP Without Accidental Matches

How to find a whole word in a string in PHP without accidental matches?

You can use a regular expression to easily achive the goal.

Example #2 from the documentation of preg_match:

/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

Note that the above example uses the i modifier, which makes the search for "web" case insensitive.

Find case insensitive word or sentence in a body of text - PHP

You can use this example below.

<?php
$textYouAreSearchingFor = "vestibulum";

$fullBody = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget tempus lorem. Donec sagittis massa dui, sed consequat eros suscipit quis. Curabitur accumsan tortor eu vulputate volutpat. Ut accumsan odio justo, vitae semper nunc tristique sed. Pellentesque sit amet leo bibendum, finibus metus a, elementum tortor. Etiam finibus efficitur ligula ac vulputate. Proin vitae tristique arcu. Curabitur vestibulum libero ante, gravida blandit tortor gravida in. Curabitur tincidunt rhoncus nisi in mattis. Phasellus fermentum magna eu nibh aliquet, non sagittis erat tem ....';

if(stristr($fullBody, $textYouAreSearchingFor) !== FALSE) {
echo "Hey, we found '{$textYouAreSearchingFor}' in full body text";
}
?>

PHP strpos - search only full words

Try this regex.

https://regex101.com/r/Evd3iF/1

$re = '/\b[Aa]ny\b/';
$str = 'Company any any. Any, ';

If(preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0)){
//string contains word
}

// Print the entire match result
var_dump($matches);

The word to pattern can be made with

$pattern = "/\b[" . strtoupper(Substr($word,0,1)) . strtolower(Substr($word,0,1)) . "]" . Substr($word,1);

Please note I wrote this answer on my phone, so I may have made a mistake in the above pattern

How to find full words only in string

To see if a particular word is in a string, you can use a regular expression with word boundaries, like so:

$str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search = "KUALA";

if (preg_match("/\b$search\b/", $str)) {
// word found
}

Here \b means "boundary of a word". It doesn't actually match any characters, just boundaries, so it matches the edge between words and spaces, and also matches the edges at the ends of the strings.

If you need to make it case-insensitive, you can add i to the end of the match string like this: "/\b$search\b/i".

If you need to know where in the string the result was, you can add a third $matches parameter which gives details about the match, like this:

if (preg_match("/\b$search\b/", $str, $matches)) {
// word found
$position = $matches[1];
}

PHP to search a word within txt file and echo the whole line

This answer doesn't take into account fields in your source data, since at the moment you're just bulk-matching the raw text and interested in getting full lines. There is a much simpler way to accomplish this, ie. by using file that loads each line into an array member, and the application of preg_grep that filters an array with a regular expression. Implemented as follows:

$lines = file('ids.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); // lines as array

$search = preg_quote($_POST['search'], '~');
$matches = preg_grep('~\b' . $search . '\b~', $lines);

foreach($matches as $line => $match) {
echo "Line {$line}: {$match}\n";
}

In related notes, to match only complete words, instead of substrings, you need to have word boundaries \b on both sides of the pattern. The loop above outputs both the match and the line number (0-indexed), since array index keys are saved when using preg_grep.

How to retrive exact number from string in PHP?

You can try with this pattern

$str = "4000+a1";
preg_match_all('/\b\d+\b/', $str, $matches);
return $matches;

\b - asserts position at a boundary

\d+ - matches a digit, one to unlimited times

Find all phrases enclosed with ( ) and words without ( ) in an expression

The right side of the alternation should not have regex delimiters - the regex delimiters should only be around the entire pattern (next to the PHP string delimiters). Eg

"([^"]+)"|\w+(?:-\w+)*

If you want to capture all matches at once, without capture groups, you can use

(?<=")\b[^"]+(?=")|\w+(?:-\w+)*

https://regex101.com/r/nP6wM5/10

To exclude NOT and OR in the regex itself, use:

(?<=")\b[^"]+(?=")|\b(?!(?:NOT|OR)(?!-))\w+(?:-\w+)*

to negative lookahead for them right before matching the standalone words.

I want replace He with She with php regular expressions

have you tried with space ? like $patterns[0] = '/ he /';

This is your solution.

PHP preg_match_all() match all words except preposition, adjectives like other less important word in array

Build a regex with a negative lookahead anchored at the word boundary:

'~\b(?!(?:and|the|text|simply)\b)\w{3,}~'

See the regex demo

Details

  • \b - a word boundary
  • (?!(?:and|the|text|simply)\b) - no and, the, etc. as whole word is allowed immediately to the right of the current location
  • \w{3,} - 3 or more word chars.

PHP demo:

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
if (preg_match_all('/\b(?!(?:' . implode('|', $except) . ')\b)\w{3,}/', $input, $matches)) {
print_r($matches[0]);
}

Output:

Array
(
[0] => Lorem
[1] => Ipsum
[2] => dummy
[3] => printing
[4] => industry
)


Related Topics



Leave a reply



Submit