开发者

RegExp replace a specific XML/HTML TAG in PHP

I have a little script that replace some text, that come from a xml file, this is an example:

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

Obviosly the string is much more longer, but I would like to replace the <include file="*" /> with the content of the script in the filename, at time I use an explode that find

<include file="

but I think there is a better method to solve it. This is my code:

$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;
    }

I'm sure that a regexp done well can be a good replacement.


Edited to allow multiple includes and file checking.

$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;


So you wanna know what the value of the attribute file of the element include? Try:

$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

If not, please Elaborate.


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

matches "dynamiccontent.php" from your input string

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜