【问题标题】:Replace substrings between tags in a string in php替换php中字符串中标签之间的子字符串
【发布时间】:2014-02-15 23:24:02
【问题描述】:

我已经为此工作了一整天,但找不到可以像我有字符串一样替换 php 中字符串中的子字符串的解决方案

'<div>
   <h2>this is <span>String</span> found in h2 tag</h2>
   <p>Hello World</p>
   <h2>this is <span>String</span> found in h2 tag</h2>
   <p>Hello Universe</p>
   <h2>this is <span>String</span> found in h2 tag</h2>
</div>'

我想获取 h2 中的每个字符串,然后执行一些 htmlentity 替换,例如

$str = 'this is <span>String</span> found in h2 tag';
$sanitized = htmlspecialchars($str,ENT_QUOTES);

然后输出完整的字符串但被替换。

如何实现?

<div>
    <h2>this is &lt;span&gt;String&lt;/span&gt; found in h2 tag</h2>
    <p><b>Hello</b> World</p>
    <h3>this is <span>String</span> found in h2 tag</h3>
    <p><b>hello</b> Universe</p>
    <h2>this is &lt;span&gt;String&lt;/span&gt; found in h2 tag</h2>
</div>

【问题讨论】:

  • 看看这是否有帮助us2.php.net/book.dom
  • 不能有一些简单的解决方案来获取子字符串并执行一些计算然后替换吗?这似乎我将不得不返工很多。事实是,我现在已经变得愚蠢了,因为我已经为此投入了一整天的时间
  • 我会指出这个问题stackoverflow.com/questions/1732348/…
  • 虽然使用 substr 看起来更简单,但 dom 绝对是正确的解决方案。将失去的一天视为一种学习经历。

标签: php regex string dom substring


【解决方案1】:

您可以使用preg_replace_callback()。匹配&lt;h2&gt;标签的正则表达式是:

/<h2>(.+?)<\/h2>/  

如果您想匹配所有 &lt;hx&gt;tags,请改用以下内容:

/<h([1-6])(.*?)<\/h\1>/ 

在回调函数中,您可以更改匹配的字符串。例如:

$html = <<< EOH

<div>
   <h2>this is <span>String</span> found in h2 tag</h2>
   <p>Hello World</p>
   <h2>this is <span>String</span> found in h2 tag</h2>
   <p>Hello Universe</p>
   <h2>this is <span>String</span> found in h2 tag</h2>
</div>

EOH;

$html = preg_replace_callback("/<h2>(.+?)<\/h2>/", function($matches) {
    /* Convert content of <h2> tags to HTML entities. */
    $altered =  htmlspecialchars($matches[1], ENT_QUOTES);

    /* Put the converted content back inside <h2> tag and return it. */
    return str_replace($matches[1], $altered, $matches[0]);
}, $html);

$html = preg_replace_callback("/<p>(.+?)<\/p>/", function($matches) {
    /* Make match bold. */
    $altered = "<b>" . $matches[1] . "</b>";

    /* Put the converted content back inside <p> tag and return it. */
    return str_replace($matches[1], $altered, $matches[0]);
}, $html);

print $html;

上述脚本的输出为:

<div>
   <h2>this is &lt;span&gt;String&lt;/span&gt; found in h2 tag</h2>
   <p><b>Hello World</b></p>
   <h2>this is &lt;span&gt;String&lt;/span&gt; found in h2 tag</h2>
   <p><b>Hello Universe</b></p>
   <h2>this is &lt;span&gt;String&lt;/span&gt; found in h2 tag</h2>
</div>

【讨论】:

  • 哇,米卡,这真是个了不起的人。我可以用

    完全替换

    内容来更改

    中的 Hello 吗?我正在编辑我的问题,请看看是否可以

  • 除了替换 h2 内容之外,我还想将所有

    标签加粗。是否可以在您所说的相同功能中做到这一点?

  • 更新了示例以匹配其他问题。如果它回答了它批准的问号。
  • 谢谢米卡。难道不能在一个函数中同时进行粗体和html替换吗?
  • 您可以将正则表达式数组传递给 preg_replace_callback() 以便完成。问题是您还需要知道哪个正则表达式手表匹配,因为您正在对它们进行不同的转换。
猜你喜欢
  • 2019-06-21
  • 2015-04-29
  • 2013-11-26
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多