【问题标题】:Replace symbol with preg_replace用 preg_replace 替换符号
【发布时间】:2014-06-23 10:48:50
【问题描述】:

我可以使用 str_replace 替换符号吗?

假设我想要

<!-- Hello there -->

[Hello]

我可能对某些人来说很容易,仍在学习 str_replace 和 preg_replace

【问题讨论】:

  • 回答你的问题:是的,你可以。
  • 尝试使用该函数两次
  • eval.in/166044 是你要找的吗?

标签: php regex replace preg-replace


【解决方案1】:

您可以为 str_replace 函数传递两个数组。示例:

$find = array('<!-- ', ' there -->');
$replaceWith = array('[', ']');
$string = '<!-- Hello there -->';
$hello = str_replace($find, $replaceWith, $string);

检查doc

【讨论】:

    【解决方案2】:

    您可以通过preg_replace 完成此操作,

    <?php
    $string = '<!-- Hello there How are you -->';
    $pattern = "/^<!-- (\w+).*/i";
    $replacement = '[$1]';
    echo preg_replace($pattern, $replacement, $string);
    ?> //=> [Hello]
    

    它捕获紧跟在&lt;!--之后的一个或多个单词字符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多