【问题标题】:prevent line break after specific word (php)防止特定单词后的换行符(php)
【发布时间】:2014-10-07 15:39:44
【问题描述】:

我的文本很长,我想在特定关键词之后添加一个不换行。可以说:“先生”、“那个”、“一个”,唯一的问题是我不知道键后面会是什么词。 所以如果我有这样的文字:

... there is an elephant in the room ...

脚本应将其更改为:

... there is <span class="no-wrap">an elephant</span> in <span class="no-wrap"> the room</span> ...

我知道应该使用某种正则表达式来完成,但我真的不擅长这些。那么关于如何在 php 中执行此操作的任何提示?

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    Mr.thean 字符串以及以下单词捕获到一个组中。

    (\b(?:Mr\.|the|an)\h+\S+)
    

    替换字符串:

    <span class="no-wrap">$1</span>
    

    DEMO

    代码:

    <?php
    $string = "... there is an elephant in the room ...";
    echo preg_replace('~(\b(?:Mr\.|the|an)\h+\S+)~', '<span class="no-wrap">$1</span>', $string)
    ?>
    

    输出:

    ... there is <span class="no-wrap">an elephant</span> in <span class="no-wrap">the room</span> ...
    

    【讨论】:

    • 使用\h*以防出现空格((?:Mr\.|the|an)\h*\S+)
    • 谢谢。像魅力一样工作;)
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多