如何替换字符串中带点号的指定单词?PHP正则替换问题
Solution
I see the issue with your regex—let's break down what's going wrong and fix it step by step.
Why Your Current Regex Fails
- Typo: You have
instead of\bfor the closing word boundary (that’s probably a formatting error when you wrote the question, but it would break the regex). - Over-matching: Your regex
\b(муқ\.?)\bmatches both standaloneмуқandмуқ.as whole words. This is why the standaloneмуқinмуқ томуқ.gets replaced (which you don’t want), and it also matchesмуқ.inмуқ.шавадbecause the word boundary\bexists between the dot (non-word character) and the followingш(word character).
Fixed Regex
To target only standalone муқ. instances (where the dot isn’t followed by a letter) and leave other cases untouched, use this regex:
$result = preg_replace("/\bмуқ\.(?!\p{L})/u", 'repl', $string);
How It Works
Let’s break down the components:
\b: Ensuresмуқis a standalone word (not part of a longer word likeмуқоиса).муқ\.: Matches the exact sequenceмуқ.(the dot is escaped since it’s a special regex character).(?!\p{L}): A negative lookahead that checks the character after the dot is not a Unicode letter. This prevents matchingмуқ.inмуқ.шавад(where the dot is followed byш, a letter)./u: Enables Unicode mode, which is essential for correctly handling non-Latin characters like Uzbek.
Testing Against Your Example
Original string:
$string = "муқ. - муқоиса муқ. муқ.шавад муқ томуқ.";
After replacement:
repl - муқоиса repl муқ.шавад муқ томуқ.
Which exactly matches your expected result!
内容的提问来源于stack exchange,提问作者Andreas Hunter
相关产品推荐
相关产品推荐

