【问题标题】:Replace symbol with preg_replace用 preg_replace 替换符号
【发布时间】:2014-06-23 10:48:50
【问题描述】:
我可以使用 str_replace 替换符号吗?
假设我想要
<!-- Hello there -->
到
[Hello]
我可能对某些人来说很容易,仍在学习 str_replace 和 preg_replace
【问题讨论】:
标签:
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]
它捕获紧跟在<!--之后的一个或多个单词字符