Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

preg_replace 1

Status
Not open for further replies.

jamesp0tter

Programmer
Feb 20, 2003
119
PT
i'm stuck...

imagine i have:

Code:
 $whtv_var = "[aaaaa] bbb (ccccccccc) - dddd";

so, to get those lil letters, i use:

Code:
 $As = preg_replace("'\[(.*?)\] (.*?) \((.*?)\) - (.*?)'","\$1", $whtv_var);
 $Bs = preg_replace("'\[(.*?)\] (.*?) \((.*?)\) - (.*?)'","\$2", $whtv_var);
 $Cs = preg_replace("'\[(.*?)\] (.*?) \((.*?)\) - (.*?)'","\$3", $whtv_var);
 $Ds = preg_replace("'\[(.*?)\] (.*?) \((.*?)\) - (.*?)'","\$4", $whtv_var);

right ?
the thing is... $As will contain "aaaaadddd", $Bs will have "bbbdddd", $Cs "cccccccccdddd" and $Ds "dddd"... at least in my code..

do you see my problem ? why does \$4 appear everytime ? o_O

jamesp0tter,
jamespotter@netcabo.pt

p.s.: sorry for my (sometimes) bad english :p
 
Mostly it's because you're using preg_replace() when what you really want is preg_match().

Try this on for size:

Code:
<?php
$whtv_var = "[aaaaa] bbb (ccccccccc) - dddd";

preg_match ('/\[(.*)\] (.*) \((.*)\) - (.*)/',$whtv_var, $matches);

print '<pre>';
print_r ($matches);
?>

On my LAMP (RH9/2.0.48/4.0.11/4.0.17/4.3.4) box, I get the output:

Code:
Array
(
    [0] => [aaaaa] bbb (ccccccccc) - dddd
    [1] => aaaaa
    [2] => bbb
    [3] => ccccccccc
    [4] => dddd
)

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
horray :) works fine now.. so the trick was those (.*?) -> (.*).. uhm.. well we're always learning ;)

thanks!


jamesp0tter,
jamespotter@netcabo.pt

p.s.: sorry for my (sometimes) bad english :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top