I'm a novice at regex, so hopefully some expert can just yawn at my question with an easy answer. I'm trying to find and replace words that start with a certain letter and keep them plural if they are plural.
So, for example, I want to replace replace the word "boy" with "band", and "boys" with "bands"
text.replace( /\b(b)[\w]+(s?)\b/gi, "<span style=\"font-weight:bold\">$1and$2<\/span>" );
However, $2 isn't coming up with the optional "s".
Thanks ahead of time!
Simply change [\w]+
to [\w]+?
.
This changes
from "greedy" (match as many characters as possible and only give characters up if forced to)
which means s?
will not match because [\w]+
already did it for us. (wrong behavior)
to "lazy" (match as few characters as possible, only adding to the match if absolutely necessary)
which gives s?
an opportunity to match. (correct behavior)
By the way: You can change [\w]+?
to \w+?
and it will work exactly the same.
[\w]+
has already matched the "s". The solution is to make [\w]+
match as few as possible, instead of as many as possible, with the "?" modifier. Thus:
\b(b)[\w]+?(s?)\b
Just use the pattern like /\b(([A-Za-z]{3,})+(s))\b/
$text="boys";
echo preg_replace('/\b(([A-Za-z]{3,})+(s))\b/','$2',$text); //output "boy"
Continuing from the PHP question Regex - How to search for singular or plural version of word
If you know what your search term is, it can be pretty simple. Here's a simple example I use in PHP to highlight all occurrences of a search term whether it is singular, simple plural (s), all lowercased or first letter uppercased:
function add_highlight($content,$term)
{
//always remove last s if it exists
//and could use similar strategy to test other endings such as -es and -ies
//by conditionally building the regex test string based on term's ending
$term_no_s = rtrim($term,"s");
return preg_replace("/({$term_no_s}s)|({$term_no_s})/i", "<span class='highlight'>$0</span>", $content);
}