我需要用微笑替换图像标签{smile:smilename}
<?php
$pattern = '<img src="/img/smile/(.*?).gif">';
$replacement = '{smile:$1}';
$subject = '<div contenteditable="true" id="message_text">text<img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"><img src="/img/smile/smile3.gif"></div>';
echo preg_replace($pattern, $replacement, $subject, -1 );
?>
我明白了:
<div contenteditable="true" id="message_text">text<{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}><{smile:smile3}></div>
<{smile:smile3}>
但我需要
{smile:smile3}
答案 0 :(得分:9)
您的<
和>
被视为分隔符,而不是表达式的一部分。使用:
$pattern = '#<img src="/img/smile/(.*?).gif">#';
请参阅php.net regexp delimiters documentation(第三个代码示例和顶级用户注释)
答案 1 :(得分:6)
您需要在模式中使用分隔符并在内部转义此字符。
$pattern = '/<img src="\/img\/smile\/(.*?).gif">/';
或者
$pattern = '@<img src="/img/smile/(.*?).gif">@';