【问题标题】:Replacing append html tag values with symbol or notations用符号或符号替换附加的 html 标记值
【发布时间】:2011-12-14 05:43:37
【问题描述】:
<span class="fwb">Harry and David</span>

<span class="fcg">Business Intelligence Developer/Analyst</span> 
<span class="fcg">Oct 1998 to present</span>
<span class="fcg">Medford, Oregon</span>

<span class="fsm fwn fcg">Creative writing</span>

In my html content 
<span class="fwb"> occured more than 4 times, 
<span class="fcg"> occured more than 10 times, 
<span class="fsm fwn fcg">Creative writing</span> occured  more than 5 times. 

使用 php reg 表达式或 DOMDocument() 我需要用 $ 符号替换所有要附加的内容。

例如:

<span class="fwb">Harry and David</span> to be replaced by <span class="fwb">Harry and David$</span>

<span class="fcg">Business Intelligence Developer/Analyst</span> to be replaced by       <span class="fcg">Business Intelligence Developer/Analyst$</span>

【问题讨论】:

    标签: php dom preg-replace


    【解决方案1】:

    从您的代码示例 (?) 中很难理解,但我相信您希望在每个 &lt;span&gt; 标记的末尾附加一个 $ 符号。使用DomDocument 执行此操作:

    $str = '
    <span class="fwb">Harry and David</span>
    <span class="fcg">Business Intelligence Developer/Analyst</span>
    ';
    
    $dom = new DomDocument();
    $dom->loadHTML($str);
    
    $spans = $dom->getElementsByTagName('span');
    foreach ($spans as $span) {
      $span->nodeValue = $span->nodeValue . '$';
      echo $dom->saveHTML($span) . "\n";
    }
    

    正如你所说,你也可以像这样使用preg_replace()

    $str = '
    <span class="fwb">Harry and David</span>
    <span class="fcg">Business Intelligence Developer/Analyst</span>
    ';
    
    $p = '{(<span[^>]*>)([^<]+)(</span>)}';
    $r = '$1$2\$$3';
    echo preg_replace($p, $r, $str);
    

    此正则表达式示例将$ 附加到主题 HTML 文本中每个 span 节点的末尾。

    【讨论】:

    • 正则表达式按给定的方式工作,它解决了我的问题。 Domdocument 显示错误 DOMDocument::saveHTML() 需要 0 个参数,1 在第 20 行的 /var/www/fbcrawl/testing.php 中给出。提供学习 abt reg 表达式的最佳链接
    • 我在第一次学习使用正则表达式时使用了this source。至于 Dom 错误,这很奇怪,因为 saveHTML() 采用可选的节点参数,我在发布答案之前测试了代码...
    猜你喜欢
    • 2013-04-03
    • 2019-09-15
    • 2015-08-22
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2018-11-23
    相关资源
    最近更新 更多