Jump to content

preg_replace help


Swift-R

Recommended Posts

Can someone explain what is wrong with this code?

 

$string = "blabla <'bl'a'> hello";
$result = preg_replace( "#<'([^'>]\S+)'>#", "'" . $this->escape_string( "$1" ) . "'", $string );

 

What this is supposed to do is to pick the text inside <' and '> and do a mysql_real_escape_string ($this->escape_string) to that text.

It is displaying the $string correctly, without the < and > but escape_string isn't working. It's supposed to return blabla 'bl\'a' hello instead of blabla 'bl'a' hello.

 

I have also tried to use the function strtoupper instead of $this->escape_string but it is still not working.

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/192045-preg_replace-help/
Share on other sites

You can't call preg_replace like that (and have it do what you're expecting). The replacement string will effectively be '$1' which of course just wraps the matched value in single quotes.

 

Instead, you should use a callback function with preg_replace_callback like:

 

// The match gets fed into this function which returns the replacement string
public function escape_and_quote_match($match) {
return "'" . $this->escape_string($match[1]) . "'";
}

// How to call preg_replace_callback
$result = preg_replace("#<'([^'>]\S+)'>#", array($this, 'escape_and_quote_match'), $string);

 

Link to comment
https://forums.phpfreaks.com/topic/192045-preg_replace-help/#findComment-1012165
Share on other sites

You can't call preg_replace like that (and have it do what you're expecting). The replacement string will effectively be '$1' which of course just wraps the matched value in single quotes.

 

Instead, you should use a callback function with preg_replace_callback like:

 

// The match gets fed into this function which returns the replacement string
public function escape_and_quote_match($match) {
return "'" . $this->escape_string($match[1]) . "'";
}

// How to call preg_replace_callback
$result = preg_replace("#<'([^'>]\S+)'>#", array($this, 'escape_and_quote_match'), $string);

 

Thank you!

 

$result = preg_replace_callback( "#<'([^'>]\S+)'>#", create_function( '$matches', 'return strtoupper($matches[1]);' ), $string);

 

But if I use $this->escape_string($matches[1]); it returns this error:

 

Using $this when not in object context in ... : runtime-created function on line 1

 

Guess I'll have to use your example.

Link to comment
https://forums.phpfreaks.com/topic/192045-preg_replace-help/#findComment-1012187
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.