Dzmitry
Dzmitry

Reputation: 215

Remove part of string by pattern

I have a string. I need to remove render_dynamic_content(, leave the text and then remove next ) from the string. The text inside the pattern can be different.
Example:

some ( text {{ render_dynamic_content(dynamic_html.POS_A_IMG) }} another ) text {{ render_dynamic_content(dynamic_html.POS_B_IMG) }}

Expected result should be:

some ( text {{ dynamic_html.POS_A_IMG }} another ) text {{ dynamic_html.POS_B_IMG }}

I'm trying:

$string = 'some ( text {{ render_dynamic_content(dynamic_html.POS_A_IMG) }} another ) text {{ render_dynamic_content(dynamic_html.POS_B_IMG) }}';
$content = preg_replace('/render_dynamic_content([\s\S]+?)/', '', $string);

The result is:

some ( text {{ dynamic_html.POS_A_IMG) }} another ) text {{ dynamic_html.POS_B_IMG) }}

I need to remove ) after dynamic_html.POS_A_IMG and dynamic_html.POS_B_IMG

Upvotes: 1

Views: 47

Answers (1)

Patrick Q
Patrick Q

Reputation: 6393

You're close, but you need to include (and escape) the parenthesis in your pattern, and then put the captured part (the part you want to keep) in the replacement instead of an empty string.

$string = 'some ( text {{ render_dynamic_content(dynamic_html.POS_A_IMG) }} another ) text {{ render_dynamic_content(dynamic_html.POS_B_IMG) }}';
$content = preg_replace('/render_dynamic_content\(([\s\S]+?)\)/', '\1', $string);

echo $content;

DEMO

NOTE: Some other pattern may or may not be more efficient. For the purpose of this answer, I'm not going to try to optimize it.

Upvotes: 3

Related Questions