Reputation: 335
I am trying to use preg_match to find a certain word in a string of text.
$pattern = "/" . $myword . "/i";
This pattern will find the word "car" inside "cartoon"... I need just matches where the certain word appears.
P.S The word may be anywhere inside the text. Thanks
Upvotes: 1
Views: 9196
Reputation: 837
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREenter code hereG_OFFSET_CAPTURE, 3);
print_r($matches);
The pattern to search for, as a string.
The input string.
If matches is provided, then it is filled with the results of search. $matches[0]
will contain the text that matched the full pattern, $matches[1]
will have the text that matched the first captured parenthesized subpattern
, and so on.
flags can be the following flag:
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).
if (preg_match('/;/', $_POST['value_code']))
{
$input_error = 1;
display_error(_("The semicolon can not be used in the value code."));
set_focus('value_code');
}
Upvotes: 0
Reputation: 170158
Wrap your regex with word-boundaries:
$pattern = "/\b" . $myword . "\b/i";
or, if your $myword
may contain regex-meta-chars, do:
$pattern = "/\b" . preg_quote($myword) . "\b/i";
Upvotes: 5
Reputation:
Try this:
$pattern = "/\b" . $myword . "\b/i";
In regular expressions, the \b
escape character represents a "word boundary" character. By wrapping your search term within these boundary matches, you ensure that you will only match the word itself.
Upvotes: 0