Preg_replace keeping wildcards?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
SkyNT
Forum Newbie
Posts: 2
Joined: Mon Mar 14, 2011 8:16 am

Preg_replace keeping wildcards?

Post by SkyNT »

Hello,

I am trying to parse $lan_content (which contains HTML) for hyperlinks and tack on the string 'lan='.$language at the end of the hyperlink URL. I am not sure how to go about replacing the wildcards properly. At the same time I would like to know if my regex patern makes sense (assuming it will do this for all index.php pages. There's alot going on here and I am not very experienced with regex.

I expext a hyperlink to be declared either:
href="index.php?_variables_"
href="/index.php?_variables_"
href='index.php?_variables_'
href='/index.php?_variables_'

Code: Select all

preg_replace('#href=".?index.php?.*"#', '#href=".?index.php?.*lan='.$language.'"#', $lan_content);
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Preg_replace keeping wildcards?

Post by AbraCadaver »

Won't work if there is not a query string ( ?_variables_ ):

Code: Select all

$new = preg_replace('#(href=([\'"]).*?index\.php\?.*?)[\'"]#', "$1&lan=$language$2", $lan_content);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
SkyNT
Forum Newbie
Posts: 2
Joined: Mon Mar 14, 2011 8:16 am

Re: Preg_replace keeping wildcards?

Post by SkyNT »

Ah yes that worked really well, thank you kind sir!

I noticed you are inserting '&lan='.$language between variables $1 and $2. $1 represents (href=([\'"]).*?index\.php\?.*?) and $2 represents [\'"] I presume? Interesting, didn't know you could do that.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Preg_replace keeping wildcards?

Post by AbraCadaver »

Those are back-references. They reference a capture group ( ) in order of appearance so: ($1 ($2) )
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply