Regex search and replace with optional plural

2019-02-18 15:57发布

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!

4条回答
放荡不羁爱自由
2楼-- · 2019-02-18 16:25

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"
查看更多
Viruses.
3楼-- · 2019-02-18 16:33

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);
}
查看更多
聊天终结者
4楼-- · 2019-02-18 16:35

[\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
查看更多
爷的心禁止访问
5楼-- · 2019-02-18 16:38

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.

查看更多
登录 后发表回答