Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

arrays - Preg_replace and preg_match to get and replace HTML / PHP content

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...