Jump to content

How to change all content between set of brackets.


Go to solution Solved by Ch0cu3r,

Recommended Posts

What I am doing is displaying a message to another user on the company system.

 

This is Test 1 [20345]

 

The above data is what is stored in the database.

 

What I want to acheive is when I echo the field for it to do this:

 

This is Test 1 [<a href="http://mywebsite.com/system/page1.php?number=20345">20345</a>]

 

I currently am able to make this work. However I cannot get it to work on multiple links.

$message_message = $row['message_message'];	
      preg_match("/\[(.*)\]/", $message_message , $matches);
      $match = $matches[1]; 
      $parts = explode ("[", $message_message);
      $part1 = $parts[0];
      $part2 = $parts[1];
      $subparts = explode ("]", $part2);
      $part3 = $subparts[1];
    
      if ($match != ""){
      $new_message_text2 = $part1 . "[<a href=\"http://mywebsite.com/system/page1.php?number=$match\">$match</a>]" . $part3;
      }else{
        $new_message_text2 = $message_message;
      }

When I have data like this:

This is Test 2 [20345] [20552]

 

I get a result like this:

This is Test 2 [<a href="http://mywebsitecom/system/page1.php?number=20345] [20552">20345] [20552</a>]

 

 

  • Solution

Your could use preg_replace instead

$message_message = $row['message_message'];	

$message_message = preg_replace("/\[(\d+)\]/", '[<a href=\"http://mywebsite.com/system/page1.php?number=$1">$1</a>]', $message_message);

Worked Like a Charm!

 

Also cleaned my code up a lot!

 

JCBones I will look into preg_replace_all for future use. Thank you.

 

 

Your could use preg_replace instead

$message_message = $row['message_message'];	

$message_message = preg_replace("/\[(\d+)\]/", '[<a href=\"http://mywebsite.com/system/page1.php?number=$1">$1</a>]', $message_message);
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.