General Community > Scripting Help

preg_replace help...

(1/4) > >>

Tyris:
Hi...
I've never really used preg_replace before... just found out about its... awesome power ;D ;D
anywho... following code:

--- Code: ---$newcontent .= preg_replace("/<~jcME~(.+?)~>/", $dataarray[$name][$i][($1)], $inner);
--- End code ---
basically...
I want it to replace the tag that looks like:
<~jcME~KeyWord~> with the data thats stored in $dataarray[$name][$i][KeyWord]
basically... it doesn't seem to like the "$1"... refuses to accept it as a value... and when I enclose it in " tags like so

--- Code: ---$newcontent .= preg_replace("/<~jcME~(.+?)~>/", "$dataarray[$name][$i][$1]", $inner);
--- End code ---
it prints
Array[$name][$i][KeyWord]
so.. the keyword is printed.. but none of its included in the array call...

Also... anyone know any links for preg_replace and regex in general... coz I've got no idea when it comes to it... yet it seems incredibly powerful (would make my scripts about 1 tenth in length...)

Thanx a Heap!


*edit*
well... after refreshing the SMF forums about 20 times... ;D and serching through the preg_replace page at php.net another 10 times... I managed to find that if I chuck in "/e" at the end of the pattern, and a "\" before each of the "$"'s in the array's it all works... dunno how... but sweeeet!!!
at last  8)

ie:

--- Code: ---          $newcontent .= preg_replace("/<~jcME~(.+?)~>/e", "\$dataarray[\$name][\$i]['\\1']", $inner);
--- End code ---

Parham:
I would have sent it to a function (it at least looks much better that way :))

[Unknown]:
FUNCTION?!  Way to chew dirt :P.

$newcontent .= preg_replace('/<~jcME~([^~]+)~>/e', '$dataarray[$name][$i]["$1"]', $inner);

Might be the most optimized way of doing it...

-[Unknown]

Tyris:
heheh, knew I could count on you guys to gimme a hand even if I had fixed my own problem ;D (just a shame you woulda all been asleep when I posted it... heheh, goes with living in Aus I guess)

@ Parham - That's what I've been doing for most of my scripts... running it through a parser to get the front of the tag, and the end, and the bit in the middle... and use the bit in the middle... problem is its a few lines... and far slower I believe.

@ [Unknown] - I tried that 'optimized' way without using the /e... and it printed Array[KeyWord] instead of the actual element...
or does the /e fix everything...?
what does the 'e' actually do :-[ ???
heheh, and any tutorials you know of for for all this regex stuff? I guess I'll try re-reading the php.net page stuff a few times (I swear... this is the only time I've had trouble understanding php funtions  :o)

Parham:
Well.. it does LOOK better :P

Navigation

[0] Message Index

[#] Next page

Go to full version