RegExp заменяет определенный тег XML / HTML в PHP - PullRequest
0 голосов
/ 28 сентября 2010

У меня есть небольшой скрипт, который заменяет некоторый текст из файла 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 ]

1 голос
/ 28 сентября 2010

Итак, вы хотите знать, что входит в значение атрибута файла элемента? Попробуйте:

$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

Если нет, пожалуйста, уточните.

1 голос
/ 28 сентября 2010
/(?<=<include file=").+(?=")/

соответствует «dynamiccontent.php» из вашей входной строки

1 голос
/ 28 сентября 2010

Отредактировано , чтобы разрешить множественные включения и проверку файлов.

$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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...