douwen4401 2013-07-30 22:01
浏览 302
已采纳

PHP preg_replace跳过匹配重叠的地方

I've been Googling this regex behavior all afternoon.

$str = ' b c d w i e f g h this string';

echo preg_replace('/\s[bcdefghjklmnopqrstuvwxyzBCDEFGHJKLMNOPQRSTUVWXYZ]{1}\s/', ' ', $str);

I want to remove all instances of a single character by itself (except for A and I) and leave one space in its place. This code appears to work on every other match. I suspect this is because the matches overlap each other.

I suspect a lookaround would be appropriate here, but I've never used them before and could use a snippet.

EDIT: Just to avoid confusion about what I am trying to accomplish. I want to turn the above string into this:

$str = ' i this string';

Notice all single-letter characters that are NOT "A" or "I" have been removed.

  • 写回答

3条回答 默认 最新

  • douchunjing6587 2013-07-30 22:11
    关注

    You can try this:

    /(?<=\s)[b-hj-zB-HJ-Z](?=\s)/
    

    or modify the ranges if you dont need both i and I.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi