Mac Taylor
Mac Taylor

Reputation: 5148

replace special strings in a html page by php

I am looking for a way to replace all string looking alike in entire page with their defined values

Please do not recommend me other methods of including language constants.

Strings like this :

[_HOME]

[_NEWS]

all of them are looking the same in [_*] part

Now the big issue is how to scan a HTML page and to replace the defined values .

One ways to parse the html page is to use DOMDocument and then pre_replace() it

but my main problem is writing a pattern for the replacement

$pattern = "/[_i]/";
$replacement= custom_lang("/i/");
$doc = new DOMDocument();
$htmlPage = $doc->loadHTML($html);

preg_replace($pattern, $replacement, $htmlPage);

Upvotes: 0

Views: 158

Answers (2)

Shubham
Shubham

Reputation: 22317

In RegEx, [] are operators, so if you use them you need to escape them.

Other problem with your expression is _* which will match Zero or more _. You need to replace it with some meaningful match, Like, _.* which will match _ and any other characters after that. SO your full expression becomes,

/\[_.*?\]/

Hey, why an ?, you might be tempted to ask: The reason being that it performs a non-greedy match. Like,

[_foo] [_bar] is the query string then a greedy match shall return one match and give you the whole of it because your expression is fully valid for the string but a non-greedy match will get you two seperate matches. (More information)

You might be better-off in being more constrictive, by having an _ followed by Capital letters. Like,

/\[_[A-Z]+\]/

Update: Using the matched strings and replacing them. To do so we use the concept called back-refrencing.

Consider modifying the above expression, enclosing the string in parentheses, like, /\[_([A-Z]+)\]/

Now in preg-replace arguments we can use the expression in parentheses by back-referencing them with $1. So what you can use is,

preg_replce("/\[_([A-Z]+)\]/e", "my_wonderful_replacer('$1')", $html);

Note: We needed the e modifier to treat the second parameter as PHP code. (More information)

Upvotes: 2

Nick
Nick

Reputation: 6346

If you know the full keyword you are trying to replace (e.g. [_HOME]), then you can just use str_replace() to replace all instances.

No need to make things like this more complex by introducing regex.

Upvotes: -1

Related Questions