【问题标题】:Keeping upper or lower case while performing str_replace [ PHP 8.0 ]执行 str_replace 时保持大写或小写 [ PHP 8.0 ]
【发布时间】:2022-01-18 19:59:25
【问题描述】:

我现在下达命令:

<?php echo str_ireplace( $url['word']['word'] , ( '<strong>' . $url['word']['word'] . '</strong>' ) , $url['word']['question'] ); ?></p>

我在我的网站的“每日词汇”部分使用它。目的是在网页上查看时,正在使用的单词以粗体显示。例如:

What is the next **Aspiration** in your life you are working towards?

我真正想做的是找到一种更好的方法来在当天的单词周围插入&lt;strong&gt; 标签。目前,我已经将单词全部大写。我对在实际表格中包含 HTML 犹豫不决,因此我可以根据将来的任何编程更改适当地格式化它。在上面的例子中,Aspiration 是大写的。但是数据库中的“问题”是:

What is the next aspiration in your life you are working towards?

我的数据库表结构是:

reference bigint
word text
question text
add_date timestamp with time zone
membership_reference

有没有更好的方法来添加&lt;strong&gt;&lt;/strong&gt; 标签?

【问题讨论】:

    标签: php html search str-replace


    【解决方案1】:

    您需要检查单词边界,而不仅仅是任意匹配。注意如果你的词是 aspiration 并且你的句子是:

    What is the next exaspiration in your life you are working towards?
    

    然后你得到一个部分匹配:

    What is the next ex<strong>aspiration<strong> in your life you are working towards?
    

    为避免这种情况,您可以使用\b 正则表达式模式,并且为了使其不区分大小写,您可以使用/i 修饰符。然后,为了保留被替换单词的大小写,用括号捕获匹配的文本并替换为匹配的文本占位符\1,而不是原始源单词的任何大小写:

    preg_replace('/\b(' . $word . ')\b/i', '<strong>\1</strong>', $question);
    

    这会产生:

    This <strong>aspiration</strong> is lowercase.
    <strong>Aspiration</strong> remains caps here.
    But exaspiration does not get tagged.
    

    我还建议使用 &lt;span class="word-of-the-day"&gt; 之类的东西而不是 &lt;strong&gt; -- 这样您就可以在 CSS 中更改样式,而不必编辑源代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      相关资源
      最近更新 更多