/    Sign up×
Community /Pin to ProfileBookmark

Replace with Dynamic variable in preg_replace

Hi
I’m trying the following code:

[code]$t = ’12<– AB_C –>’;
$AB_C = ‘abc’;
echo preg_replace(‘/<– ([A-Z_]+) –>/’, “$$1”, $t);[/code]

I want to get “12abc” , but it outputs: 12$AB_C , so, it not recognize the replacement as dynamic variable.
Is it any way to use the matched word in preg_replace() as a variable, or dynamic variable?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@hyperionXSFeb 20.2012 — Use replace() instead
[CODE]
$t = '12<-- AB_C -->';
$AB_C = 'abc';
alert( $t.replace(/<-- AB_C -->/i, $AB_C) )
[/CODE]
Copy linkTweet thisAlerts:
@MarPloauthorFeb 20.2012 — Use replace() instead
[CODE]
$t = '12<-- AB_C -->';
$AB_C = 'abc';
alert( $t.replace(/<-- AB_C -->/i, $AB_C) )
[/CODE]
[/QUOTE]

Hi

alert() is not in PHP, your example is wrong.

AB_C is not known, it is got with regexp.
Copy linkTweet thisAlerts:
@hyperionXSFeb 20.2012 — Oh, sorry, I thought it was JavaScript.

For PHP use str_replace
[CODE]
$t = '12<-- AB_C -->';
$AB_C = 'abc';
echo str_replace('<-- AB_C -->', $AB_C, $t)
[/CODE]
Copy linkTweet thisAlerts:
@MarPloauthorFeb 20.2012 — For those who look for a solution to this problem, the '/e' flag, which evalates the replacement, solved the problem, and returns the results i want, using:
preg_replace('/&lt;-- ([A-Z_]+) --&gt;/e', "$$1", $t);
×

Success!

Help @MarPlo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...