【问题标题】:How to detect certain characters and wrap them with another string?如何检测某些字符并用另一个字符串包装它们?
【发布时间】:2013-08-26 05:52:51
【问题描述】:

我对 php 中的 html 字符串有疑问

我想检测字符串是否包含<tbody>,如果是,则用<table></table>标签包裹

我的字符串会是这样的:

<tbody>
   <tr>
      <td>cell</td>
      <td>cell</td>
   </tr>
   <tr>
       <td>cell</td>
      <td>cell</td>
   </tr>
</tbody>

问题不是每个字符串都包含&lt;tbody&gt;,我需要检测它是否有&lt;tbody&gt;标签

我只需要用&lt;table&gt; 包装字符串,这样我就可以将电子邮件发送给客户。

感谢您的帮助!

【问题讨论】:

  • 在处理以字符串形式序列化的结构化数据时,应避免“愚蠢”的字符串操作。相反,使用DOMDocument 将字符串转换为结构化表示,DOMXPath 查找&lt;tbody&gt; 节点并将它们包装在&lt;table&gt; 中(如果它们的父节点还不是一个)。

标签: php


【解决方案1】:

使用DOMDocumentDOMXPath

<?php
$dom = new DOMDocument();
$dom->loadHTML("<tbody>
   <tr>
      <td>cell</td>
      <td>cell</td>
   </tr>
   <tr>
       <td>cell</td>
      <td>cell</td>
   </tr>
</tbody>");

$xpath = new DOMXpath($dom);
$result = $xpath->query('//tbody');

if ($result->length > 0) {
    //tbody found
}

?>

See it live!

【讨论】:

    【解决方案2】:

    请查看SimpleXML,它允许加载、操作和保存 XML:

    使用示例 [source of sample]:

    <?php
    include 'example.php';
    $xml = new SimpleXMLElement($xmlstr);
    
    $character = $xml->movie[0]->characters->addChild('character');
    $character->addChild('name', 'Mr. Parser');
    $character->addChild('actor', 'John Doe');
    
    $rating = $xml->movie[0]->addChild('rating', 'PG');
    $rating->addAttribute('type', 'mpaa');
    
    echo $xml->asXML();
    ?>
    

    根据这些数据:

     <?xml version='1.0' standalone='yes'?>
      <movies>
       <movie>
        <title>PHP: Behind the Parser</title>
        <characters>
          <character>
            <name>Ms. Coder</name>
            <actor>Onlivia Actora</actor>
            </character>
          <character>
            <name>Mr. Coder</name>
            <actor>El Act&#211;r</actor>
          </character>
         </characters>
        </movie>
       <movies>
    

    SimpleXML 的DOM methods 可能也很有趣。

    【讨论】:

    • 这不是 xml。它只是一个从客户端返回的简单 html 字符串。 +1 虽然
    猜你喜欢
    • 2011-03-31
    • 2011-02-21
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2016-08-09
    • 2017-06-25
    相关资源
    最近更新 更多