Preg_replace和preg_match获取和替换HTML / PHP内容
问题描述:
我需要提取一些HTML / PHP内容并将其放入数组中。
I need to extract some HTML / PHP content and put it into an array.
这就是我所拥有的
下面的代码例如在名为$ string的字符串中。
The code below is within a string called $string for example.
<html>
<?php myclass->my_function('First', 'Last'); ?>
<p>Some other content</p>
<?php myclass->my_function(1, 2, 3); ?>
</html>
我想从函数中找到所有值,并将它们求和成带有preg_match的数组。只能找到myclass-> my_function函数值。
I want to find all the values from the functions and sum them into an array with preg_match. Only myclass->my_function function values should be found.
数组应如下所示
$array = array(
1 => array('First', 'Last'),
2 => array(1,2,3),
);
然后我要preg_replace用[explode_id]替换所有行,结果应该是:
Then I want preg_replace to replace all the rows with [explode_id] and the result should be:
<html>
[explode_1]
<p>Some other content</p>
[explode_2]
</html>
谢谢!
答
$str = '<html>
<?php myclass->my_function(\'styles\', \'home.css\'); ?>
<p>Some other content</p>
<?php myclass->my_function(1, 2, 3); ?>
</html>';
function jens($matches)
{
$path = '';
$parts = explode(',', $matches[1]);
foreach($parts as $match)
$path .= '/' . str_replace('\'', '', trim($match));
return $path;
}
$replaced = preg_replace_callback('/<\?php myclass->my_function\((.*?)\); \?>/', 'jens', $str);
echo $replaced;
应该做你想做的事。