问题
I need to extract some HTML / PHP content and put it into an array.
Here is what I have
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>
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.
The array should look like this
$array = array(
1 => array('First', 'Last'),
2 => array(1,2,3),
);
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>
Thanks!
回答1:
$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;
Should do what you want.
回答2:
$match_array = preg_match('/<\?php myclass->my_function\((.+?)\); \?>/', $input_string, $matches);
$output_arrays = array();
$output_arrays[] = eval('array('.$matches[0][1].')';
$output_arrays[] = eval('array('.$matches[1][1].')';
echo '<html>';
echo implode(' ', $output_arrays[0]);
echo '<p>Some other content</p>';
echo implode(' ', $output_arrays[1]);
echo '</html>';
来源:https://stackoverflow.com/questions/4727191/preg-replace-and-preg-match-to-get-and-replace-html-php-content