【问题标题】:RegExp replace a specific XML/HTML TAG in PHPRegExp 替换 PHP 中的特定 XML/HTML TAG
【发布时间】:2010-09-28 08:16:31
【问题描述】:

我有一个小脚本可以替换一些来自 xml 文件的文本,这是一个示例:

<b>Hello world,</b>
<include file="dynamiccontent.php" />
<img src="world.png" />
a lot of <i>stuff</i>

显然字符串要长得多,但我想用文件名中脚本的内容替换<include file="*" />,当时我使用了一个发现

<include file="

但我认为有更好的方法来解决它。 这是我的代码:

$arrContent = explode("<include ", $this->objContent->content);
    foreach ($contenuto as $piece) { // Parsing array to find the include
        $startPosInclude = stripos($piece, "file=\""); // Taking position of string file="
        if ($startPosInclude !== false) { // There is one
            $endPosInclude = stripos($piece, "\"", 6);
            $file = substr($piece, $startPosInclude+6, $endPosInclude-6);
            $include_file = $file;
            require ($include_file); // including file
            $piece = substr($piece, $endPosInclude+6);
        }
        echo $piece;
    }

我确信一个做得好的正则表达式可以是一个很好的替代品。

【问题讨论】:

    标签: php xml regex tags


    【解决方案1】:

    已编辑以允许多个包含和文件检查。

    $content = '<b>Hello world,</b>
    <include file="dynamiccontent.php" />
    <img src="world.png" />
    a lot of <i>stuff</i>';
    
    preg_match_all('!<include file="([^"]+)" />!is', $content, $matches); 
    if(count($matches) > 0)
    {
        $replaces = array();
        foreach ($matches[1] as $file)
        {
            $tag = '<include file="'.$file.'" />';
            if(is_file($file) === true)
            {   
                ob_start();
                require $file;
                $replaces[$tag] = ob_get_clean();
            } 
            else
            { 
                $replaces[$tag] = '{Include "'.$file.'" Not Found!}';
            }
        } 
        if(count($replaces) > 0)
        {
            $content = str_replace(array_keys($replaces), array_values($replaces), $content);
        }
    }
    
    echo $content;
    

    【讨论】:

      【解决方案2】:

      所以你想知道元素的属性文件的值包括什么?试试:

      $sgml = <<<HTML
      <b>Hello world,</b>
      <include file="dynamiccontent.php" />
      <img src="world.png" />
      a lot of <i>stuff</i>
      HTML;
      
      preg_match('#<include file="([^"]+)"#',$sgml,$matches);
      
      print_r($matches[1]); // prints dynamiccontent.php
      

      如果不是,请详细说明。

      【讨论】:

      • 是的,这很好,但在这种情况下,我只能提取文件名,而不加载其他内容,如果你看到字符串包含一些 html 标记和文本..
      • mh.. 我可以用一个简单的替换来替换包含.. :s
      【解决方案3】:
      /(?<=<include file=").+(?=")/
      

      匹配您输入字符串中的“dynamiccontent.php”

      【讨论】:

        猜你喜欢
        • 2012-10-15
        • 2013-12-30
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        • 2011-05-01
        • 2023-03-06
        相关资源
        最近更新 更多