Jump to content

[SOLVED] I wish to use preg match to match two or more keywords,


ted_chou12

Recommended Posts

using preg match to match two or more keywords, so that the result is not limited by the position of the words, and is there a way to make preg match case insensitive?

So that when searching for "good bad":

This is Good and Bad

would match instead of just:

This is good bad

Thanks. :D

Ted

Link to comment
Share on other sites

<pre>
<?php

$string = 'This is Good and Bad';
$search = 'good bad';

// Separate words
$words = preg_split('/\s+/', $search);
// Loop through words
foreach ($words as $word) {
	// Build pattern
	$pattern = '/\b' . preg_quote($word, '/') . '\b/i';
	// Execute
	echo "Looking for <b>$word</b> with <b>$pattern</b>...";
	echo preg_match($pattern, $string) ? 'Matched' : 'Did not match' ;
	echo '<br>';
}
?>
</pre>

Link to comment
Share on other sites

From the manual:

 

\b

word boundary

\B

not a word boundary

 

"A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively."

 

\w

any "word" character

\W

any "non-word" character

 

"A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w."

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.