...

View Full Version : Regex Problem



FuZion
07-09-2007, 02:29 PM
Hello,

I'm having some trouble with preg_replace. Here is the line... (I have tried both of these)

preg_replace( "<\{(.+?)\}>", tab("$1"), $text );
preg_replace( "<\{(\w+)\}>", tab("$1"), $text );

It is supposed to find {anythinginhere}, save the "anythinginhere" in $1 and then replace it with text returned from the tab() function.

Unfortunately, the text is not replaced, and I cannot for the life of me figure out why.. I have used a regex editor and it works fine but when it is run in the script it does not replace anything.

Thanks in advance!

FuZion

Serex
07-09-2007, 03:25 PM
function mTab($fNum)
{
$total = $fNum * 4;
return $total;
}

$text = "{anythinginhere}";
echo preg_replace('/\{(.*?)\}/i', "{" . mTab(5) . "}", $text);


Created my own function to test with as i don't have a copy of your tab(), seems too work for me.

FuZion
07-09-2007, 06:03 PM
Well, in your script the mTab function accepts any number.. however my script uses a backreference ( $1 ) for the function.

The tab function has an ASSOC array in it and all it does is pull the array value from $1.

GJay
07-09-2007, 06:35 PM
your regexp is missing delimiters (the /s in Serex's code), and you probably want to be using preg_replace_callback() - http://php.net/preg-replace-callback if you want to be using the backref

FuZion
07-09-2007, 11:35 PM
The <>s in my code also act as delimiters, I have tried it with the slashes also. The thing is, I have seen scripts before in a bb code parser that uses a backreference to $1, $2, ect. But for some reason this does not work.

schleppel
07-10-2007, 12:14 AM
The "e" modifier. (http://uk3.php.net/manual/en/function.preg-replace.php#id6372355)


<?php

$test_string = '{one} stuff {two}

{three} stuff {four}';

function tab($key)
{
$tab = array('one' => 'abc', 'two' => 'def', 'three' => 'ghi');
if(isset($tab[$key])) return $tab[$key];
else return $key;
}

echo preg_replace('#\{(.*?)\}#e', 'tab("\1")', $test_string);

FuZion
07-10-2007, 05:40 AM
Ok that works, thanks a lot! But now there is another problem.. if I run this once with one query, and then run another, it does not replace it.. and I cannot figure out why, I know for sure that the array. Why would it not work the second time?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum