douhui9192 2015-05-08 10:18
浏览 26
已采纳

preg_match仅在找到时显示替换

The title must be very confusing, but I have to admit, so am I when it comes to regex. My problem is the following:

I have an input string like:

{a href=www.google.com}Google{/a} {b}boldText{/b}

What I want to achieve is following:

<a href="www.google.com">Google</a> <b>boldText</b>

I have the following preg_replace function:

$input = preg_replace('/\{(\/)?'.$tag.'( [a-z]*\=)?([a-zA-Z0-9\.\:\/]*)?\}/', '<$1'.$tag.' $2"$3">', $input);

Where the tag is f.e. a or b or script. The code is working so far, the only problem is that a tag without any attributes comes out like this:

<a href="www.google.com">Google</a> <b "">boldText</b>

Can I somehow add an if condition around the $2"$3" in the replacement argument of the preg_match function, and if so, how can I do it?

  • 写回答

2条回答 默认 最新

  • dongyunqin7307 2015-05-08 10:30
    关注

    I'd merge the 2 optional groups into 1 and use a 2nd preg_replace to add double quotation marks around the attribute values inside opening tags. We cannot do it in 1 go as the replacement pattern is different for tags with attributes.

    $input = preg_replace('/\{(\/)?'.$tag.'( [a-z]*\=[a-zA-Z0-9\.\:\/]*)?\}/', '<$1' . $tag . '$2>', $input);
    

    See demo on IDEONE

    <?php
    $tag = "a";
    $str = "{a href=www.google.com at=val}Google{/a} {b}boldText{/b}";
    $input = preg_replace('#\{(\/)?' . $tag . '\b((?:\s+[a-z]*\=[a-zA-Z0-9\.\:\/]*)*)\}#', '<$1' . $tag . '$2>', $str);
    $result = preg_replace("#(?:(<".$tag.")\b|(?<!^)\G)(\s*[^\s=>]+?)=([^=>\s]*)(?=.*?>)#", "$1$2=\"$3\"", $input);
    echo $result;
    

    Output: <a href="www.google.com" at="val">Google</a> {b}boldText{/b}

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

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大