Split and replace things with PHP and preg_replace instead of explode?
I have a PHP + HTML code as a string containing functions. I want some function calls to be replaced with included content. Put together many files to one.
Short example - Before
<html>
<?php myclass->my_function('one', 'two', 'three'); ?>
<h1>Content in between</h1>
<?php myclass->my_function('1', '2'); ?>
</html>
Short example - Replacing content
<html>
<?php run('one', 'two', 'three'); /* Run does include a file */ ?>
<h1>Content in between</h1>
<?php run('1', '2'); /* Run does include a file */ ?>
</html>`
Short example - After
<html>
<?php
/* Start my_function */
echo 'This is the result of my_function one two three';
/* End my_function
?>
<h1>Content in between</h1>
<?php
/* Start my_function */
<?php myclass->my_function('four', 'five', 'six'); ?>
/* End my_function
?>
</html>
Notice that myclass is found in the included content. The result needs to be parsed again.
Short example - After that
The whole this is parsed again and it replaced the myclass with included content.
<html>
<?php
/* Start my_function */
echo 'This is the result of my_function one two three';
/* End my_function */
?>
<h1>Content in between</h1>
<?php
/* Start my_function */
echo 'four five six开发者_运维知识库';
/* End my_function */
?>
</html>
I tried to do this with explode but it went to complex. The two steps "Replacing content" and "After" might need to be done in one move.
Look at it as a string. Can preg_replace solve this? How?
$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.
精彩评论