tags:

views:

48

answers:

3

Hi all, 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.

+1  A: 

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;
buggedcom
simply wonderful ^^
Paper-bat
+1  A: 

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.

Hannes
Yeah, this is good but in this case I can only extract the file name, without loading the other content, if you see the string contains some html tag and text..
Paper-bat
mh.. I can replace the include with a simple replacement.. :s
Paper-bat
+1  A: 
/(?<=<include file=").+(?=")/

matches "dynamiccontent.php" from your input string

El Ronnoco