Weston Watson
Weston Watson

Reputation: 5724

preg_replace data between html tags

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);

Upvotes: 1

Views: 1797

Answers (3)

Donut
Donut

Reputation: 112795

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.

Upvotes: 0

fire
fire

Reputation: 21531

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.

Upvotes: 1

salathe
salathe

Reputation: 51950

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.

Upvotes: 0

Related Questions