[英]Strip leading and trailing whitespaces within a string matched using regex in php
I have a html string 我有一个html字符串
$html = <p>I'm a para</p><b> I'm bold </b>
Now I can replace the bold tags with wiki markup(*) using php regex as: 现在,我可以使用php regex将粗体标签替换为wiki markup(*):
$html = preg_replace('/<b>(.*?)<\/b>/', '*\1*', $html);
Apart from this I also want the leading and trailing whitespaces in the bold tag removed in the same php's preg_replace
function. 除此之外,我还希望在同一php的
preg_replace
函数中删除粗体标记中的前导和尾随空格。
Can anyone help me on how to do this? 谁能帮助我该怎么做?
Thanks in advance, 提前致谢,
Varun 瓦伦
Use \\s
symbol for that ( \\s*
means that there could be 0 or more occurrences): 为此使用
\\s
符号( \\s*
表示可能出现0次或多次):
$html = preg_replace('/\<b\>\s*(.*?)\s*\<\/b\>/i', '*\1*', $html);
-I also suggest to use i
modifier since html tags are case insensitive. -我也建议使用
i
修饰符,因为html标记不区分大小写。 And, finally, symbols <
and >
should be escaped for more safety (they are part of some regex construsts. Your regex will work without escaping them, but it's a good habit to escape them so be sure to avoid errors with that) 最后,为了更安全起见,应转义符号
<
和>
(它们是某些regex construsts的一部分。您的regex可以在不逃脱转义的情况下工作,但这是逃避它们的好习惯,因此请确保避免发生错误)
(edit): it seems I've misunderstood 'trailing/leading' sense. (编辑):似乎我误解了“尾随/领先”的意思。
Try using: 尝试使用:
$html = preg_replace('~<b>\s*(.*?)\s*</b>\s*~i', '*\1*', $html);
\\s
in between the tags and the string to keep will strip away the spaces to trim. 标记和要保留的字符串之间的
\\s
将去除要修剪的空格。 The i
flag just for case insensitivity and I used ~
as delimiters so you don't have to escape forward slashes. i
标志仅用于区分大小写,我使用~
作为分隔符,因此您不必转义正斜杠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.