SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2012
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question using function in the function preg_replace

    Hi
    I have a problem, I have two functions tagi() and ObrobkaTekstu. I have not idea how using function tagi in preg_replace in function ObrobkaTekstu().

    Code:
    function tagi($x)
    {
      $x=str_replace('<','&lt;',$x);
      $x=str_replace('>','&gt;',$x);
      return $x;
    }
    
    function ObrobkaTekstu($tekst_do_obrobki)
    {
      $tekst_do_obrobki=preg_replace('{\[code\](.*?)\[/code\]}s','<pre>$1</pre>',$tekst_do_obrobki);
      //....
      return $tekst_do_obrobki;
    }
    I tried this:
    Code:
    $tekst_do_obrobki=preg_replace('{\[code\](.*?)\[/code\]}s','<pre>'.tagi('$1').'</pre>',$tekst_do_obrobki);
    of course this code dosnt work.

    Who has idea?

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,313
    Mentioned
    178 Post(s)
    Tagged
    9 Thread(s)
    Hi there,

    And welcome to the forums.

    the problem with your code is that you cannot pass $1 as a parameter to a function like this, as it would be called before preg_replace is executed.
    In this case, you can use preg_replace_callback

    This will do what you want:

    Code PHP:
    function tagi($x){
      $x[1]=str_replace('<','&lt;',$x[1]);
      $x[1]=str_replace('>','&gt;',$x[1]);
      return "<pre>$x[1]</pre>";
    }
     
    function ObrobkaTekstu($tekst_do_obrobki){
      return preg_replace_callback('{\[code\](.*?)\[/code\]}s', "tagi", $tekst_do_obrobki);
    }
     
    $tekst_do_obrobki = "[code]<hello>SitepointRocks!<goodbye>[/code]";
    echo ObrobkaTekstu($tekst_do_obrobki);
    ?>

    This will output:

    HTML Code:
    <pre>&lt;hello&gt;SitepointRocks!&lt;goodbye&gt;</pre>
    I hope that helps you.

  3. #3
    SitePoint Member
    Join Date
    Dec 2012
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for your help! That's it.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •