0

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.

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

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..
mh.. I can replace the include with a simple replacement.. :s
1
/(?<=<include file=").+(?=")/

matches "dynamiccontent.php" from your input string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.