开发者

preg_replace data between html tags

开发者 https://www.devze.com 2023-01-30 12:44 出处:网络
I\'m attempting to do a preg_replace matching the data in between the html tags. this pattern works great, but I don\'t know how to get the match string.

I'm attempting to do a preg_replace matching the data in between the html tags.

this pattern works great, but I don't know how to get the match string.

preg_replace("/(?<=>)[^><]+?(?=<)/", "$1",$string);

not knowing much about regex, I'd assume that $1 would return the match, but it doesn't. now this pattern (above) can remove all data between html tags if i

preg_开发者_开发百科replace("/(?<=>)[^><]+?(?=<)/", "",$string);

my main goal is to have a line where i can put the returned match thru a function like

preg_replace("/(?<=>)[^><]+?(?=<)/", string_function("$1"),$string);


You'll want to use preg_replace_callback to apply a custom function.

Also preg_replace won't return anything I think you need preg_match.


not knowing much about regex, I'd assume that $1 would return the match, but it doesn't.

Use "$0". You're not capturing any groups, so group 1 will not exist (meaning $1 will not refer to anything). See the description of the replacement parameter in the preg_replace() docs for more about $0 and friends.

my main goal is to have a line where i can put the returned match thru a function like

To run a function on the matched string(s), you should use preg_replace_callback() instead.


Use preg_match() instead. The method signature is as follows:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

If you pass in the matches parameter, then it will get filled with the resulting matches.

E.g.:

preg_match("/(?<=>)[^><]+?(?=<)/", $string, $matches);
print_r($matches);

$matches should contain the result you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消