Jump to content

Placing text into string after certain word


Cascadia
Go to solution Solved by lemmin,

Recommended Posts

Hey there. I have a little problem that might be quite simple but is causing me much frustration.
 
I have a string of text known as $tp_desc
 
As an example I will say that the string $tp_desc contains this:
Hello this is a cool [quote]test[/quote] to figure [quote]something[/quote] out"
 
When I am putting the string $tp_desc on a webpage I want to insert a <div> tag in front of each [ quote ] and a </div> tag behind each [/ quote ]
 
So the string $tp_desc will look like this:
 
Hello this is a cool <div>[quote]test[/quote]</div> to figure <div>[quote]something[/quote]</div> out"
 
This is the code I am using to try and do this.
 
 
$b = substr($tp_desc, strpos($tp_desc, '[quote]') + 7);  // Finds the [ quote ] in the string
$c = substr($b, 0, strpos($b, '[/quote]'));  // Finds the text in between the [ quote ] and [/ quote ] tags
$replace = '<div>' . $c . '</div>'; //  Adds the <div> tags before and after the quotes
$out = str_replace($c, $replace, $tp_desc);  // Places the changed string back into the main string
echo $out; // Echos the final string

 

This seems to work but there are currently three problems. 
 
1. It only puts <div> tags around the first set of quotes and does not appear on any recurring ones.
 
2. Once the <div> tags have been added I need the original [ quote ] and [/ quote ] tags removed.
 
3. It does not work if there are two sets of quotes tags inside each other such as [ quote ] [ quote ] hello [/ quote ] what? [/ quote ]
 
Can anyone give me a little guidance on what to do here? It would be extremely appreciated  :D
Link to comment
Share on other sites

  • Solution

You can do this with a simple Regular Expression:

$tp_desc = preg_replace('/(\[quote\].+?\[\/quote\])/im', '<div>$1</div>', $tp_desc);

If you want to get rid of the

parts, just move the parentheses:
$tp_desc = preg_replace('/\[quote\](.+?)\[\/quote\]/im', '<div>$1</div>', $tp_desc);
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.