Jump to content

If Statements Inside Array Replacement


Gingechilla

Recommended Posts

My code for replacing user input is as follows:

function Replace_BB($text)
{
        $bb = array(
				'@\[u\](.*?)\[\/u\]@is',
				'@\[i\](.*?)\[\/i\]@is',
				'@\[b\](.*?)\[\/b\]@is',
				'@\[img\](.*?)\[/img\]@is',
				'@\[url\](.*?)\[/url\]@is',
				'@\[url=http://(.*?)\](.*?)\[/url\]@is'
				); 


        $html = array(
				  '<u>$1</u>',
				  '<em>$1</em>',
				  '<strong>$1</strong>',
				  '<img src="$1" />',
				  '<a href="$1">$1</a>',
				  '<a href="$1">$2</a>'
				  ); 


        return preg_replace($bb, $html, $text);

}



print_r (Replace_BB($_POST['data'])); 

 

How can I use an if statement to decide how to put in my replacement.

 

So for example:

 $html = array(
				  'IF XXXXXX THEN DO THIS>>>>> <u>$1</u>  ELSE DO THIS >>>> <u>$1 Error</u>',

Link to comment
https://forums.phpfreaks.com/topic/228850-if-statements-inside-array-replacement/
Share on other sites

Have a look at the "e" modifier for replacement strings.

 

function Replace_BB($text)
{
        $bb = array(
				'@\[u\](.*?)\[\/u\]@ise',  // ADDED THE e MODIFIER TO THIS ONE
				'@\[i\](.*?)\[\/i\]@is',
				'@\[b\](.*?)\[\/b\]@is',
				'@\[img\](.*?)\[/img\]@is',
				'@\[url\](.*?)\[/url\]@is',
				'@\[url=http://(.*?)\](.*?)\[/url\]@is'
				); 


        $html = array(
				  '"checkU(\'$1\')"',  // CHANGED THE REPLACEMENT WITH A FUNCTION CALL
				  '<em>$1</em>',
				  '<strong>$1</strong>',
				  '<img src="$1" />',
				  '<a href="$1">$1</a>',
				  '<a href="$1">$2</a>'
				  ); 


        return preg_replace($bb, $html, $text);

}

/* ADDED Callback function for preg_replace() */
function checkU($text) {
  if ($text == 'something') return '<u>' . $text . ' Error</u>';
  else return '<u>' . $text . '</u>';
}

print_r (Replace_BB($_POST['data'])); 

 

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.