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
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'])); 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.