...

View Full Version : Searching a string, then running a function once a result is found?



Immulsifier
11-16-2007, 08:49 PM
Hi

I am building a small attachments system and am wanting to search a string for all instances of [attach] and then run a function once this is found. I know I can do something like this:



$str = preg_replace("'\[b\](.*?)\[/b\]'", '<b>\\1</b>', $str);


which will replace text with <b>text</b>, but what I want to happen is when [b] for example is found, i can run a function instead of just replacing text. Can anyone give me any suggestions on how to do this.

Thanks :)

rpgfan3233
11-16-2007, 08:55 PM
Use preg_match instead? It takes the same parameters, except the replacement parameter:

if (preg_match("/\[b\](.*?)\[\/b\]/i", $str))
makeBold($str);Something along those lines?

Edit: I made it a case insensitive match since it could be [ B] or [ b].

aedrin
11-16-2007, 09:02 PM
I'm always amused when I see code that reads right, but does absolutely nothing useful.

What you need is preg_replace_callback (http://php.net/preg_replace_callback).

Immulsifier
11-16-2007, 09:16 PM
I'm always amused when I see code that reads right, but does absolutely nothing useful.

What you need is preg_replace_callback (http://php.net/preg_replace_callback).

Excellent, this is just what I was looking for :)

Immulsifier
11-16-2007, 09:24 PM
Just another quick question if you dont mind :) Say I had this:



$str = "This is the text";
$str = preg_replace_callback("'\[color=\"?(.*?)\"?](.*?)\[/color\]'", "doParse", $str);

function doParse($matches) {
echo $matches[1];
}


which works fine and outputs 990000. What I want to do is when somefile.jpg is found, use code similar to the above to run a function and then replace somefile.jpg with the results from the function. Can this be done also?

Many thanks so far.

aedrin
11-16-2007, 09:47 PM
It's a replace and a callback in one.

What you return as the result of the function will be put into the string where the match was found.

So yes, that is possible using that setup.

You might want to make your setup more dynamic though.



$pattern = '/\[(.*?)\](.*?)\[/(.*?)\]/';


So your doParse function just looks at the first match, then use a switch statement to determine what to do.

Immulsifier
11-17-2007, 01:39 AM
Thanks very much, I understand how it works now and have got it working just how I need it :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum