You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何替换字符串中带点号的指定单词?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

  1. Typo: You have  instead of \b for the closing word boundary (that’s probably a formatting error when you wrote the question, but it would break the regex).
  2. Over-matching: Your regex \b(муқ\.?)\b matches 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 \b exists 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:22:00