RegExp用PHP替换特定的XML / HTML TAG

时间:2010-09-28 08:16:31

标签: php xml regex tags

我有一个小脚本替换了一些来自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;
    }

我确信正确的正则表达式可以成为一个很好的替代品。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

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

$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

如果没有,请详细说明。

答案 2 :(得分:1)

/(?<=<include file=").+(?=")/

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