Author Topic: Different actions for different parts of a string  (Read 487 times)

0 Members and 1 Guest are viewing this topic.

Offline lwcTopic starter

  • Irregular
  • Posts: 35
    • View Profile
Different actions for different parts of a string
« on: December 17, 2009, 09:13:22 AM »

<?php
function dosomething($string$else '') {
   if (empty(
$else))
      
$string "<b>$string</b>";
   else
      
$string "<i>$string</i>";
   return 
$string;
}

$input "Some words.
[code]some code.[/code]
More words.
[quote]some code[/quote].
Other words."
;

$codetag = array('\[code\]''\[quote\]');
$codetag_rev = array('\[\/code\]''\[\/quote\]');
for (
$i 0$i count($codetag); $i++)
  
$codetag_array[] = "/([\s\S]*$codetag[$i])([\s\S]+)($codetag_rev[$i])([\s\S]*)/e";
$input_new preg_replace($codetag_array'dosomething("$1") . dosomething("$2","else") .dosomething("$3") . dosomething("$4")'$input);
echo 
"$input\n<hr>\n$input_new";
// This becomes a huge mess and $2 doesn't get saved from being bold
echo "<hr><hr>";
// It does work fine if I only try it on one tag
$input_new preg_replace($codetag_array[0], 'dosomething("$1") . dosomething("$2","else") .dosomething("$3") . dosomething("$4")'$input);
echo 
"$input\n<hr>\n$input_new";
// $2 is indeed saved from turning bold
?>

So my only question is - how do I do this for multiple tags?

Or, if you want, you can simply ignore everything until now and just tell me how do I turn $input into:


// Output:
<b>Some words.
[
code]</b><i>some code.</i>[/code]<b>
More words.
[
quote]</b><i>some code</i><b>[/quote].
Other words.</b>;


Thanks!
« Last Edit: December 17, 2009, 09:15:26 AM by lwc »

Offline printf

  • Staff Alumni
  • Devotee
  • *
  • Posts: 873
    • View Profile
Re: Different actions for different parts of a string
« Reply #1 on: December 17, 2009, 10:20:38 AM »
Replacements should be based on your tag, so if want replace a (BOLD) tag then you make a replacement for that tag, either include the replacement in that regex or create a function with a switch() or something like that function to handle all the different tags you want to support. As I side note I am not a big fan of using regular expression in my BBCODE setups because STRING BASED phasing is much faster and less resource intense. Just because most everyone else uses regular expression, doesn't mean it's the best way to do it and it not.

Offline lwcTopic starter

  • Irregular
  • Posts: 35
    • View Profile
Re: Different actions for different parts of a string
« Reply #2 on: December 17, 2009, 10:53:31 AM »
Again, I also want to replace things before/after the so called bbcode. This means part of the replacements would be outside of tags and not within them. If you have any way to reach my desired result text, please show how, whether it's regex or not.