Some regex help please?

Discussion in 'PHP' started by SniperFox.com, Nov 9, 2007.

  1. #1
    Ok, I'm not very good with regex at the moment so could some one help me. What i need is

    Say i have $str = "Random text {func-test} more random text"; i need to use preg_replace to look for {func-*} in str and then return what ever * is. So say $func = preg_replace("/{func-*}/","*",$str); Hope that makes sense.

    Thanks
     
    SniperFox.com, Nov 9, 2007 IP
  2. bobb1589

    bobb1589 Peon

    Messages:
    289
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    guessing your using this for a templating system? ... ill try and dig up what i did to solve the same problem i had
     
    bobb1589, Nov 9, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    
    preg_match("~\{func-([^\}]+)\}~", $text, $match);
    echo $match[1];
    
    PHP:
     
    nico_swd, Nov 9, 2007 IP
  4. SniperFox.com

    SniperFox.com Guest

    Messages:
    154
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Ye this is for a templating system.

    @nice_swd, The code you posted does this

    say $text = "{func-test}blahblah{func-blah}";

    it returns [0] = {func-test}, [1] = test.

    I need it to get [0] = test, [1] = blah.

    Thanks
     
    SniperFox.com, Nov 9, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    Use preg_match_all() instead of preg_match().
     
    nico_swd, Nov 9, 2007 IP
    SniperFox.com likes this.
  6. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #6
    
    <?php
    function get_funcs( $string )
    {
    	if( preg_match_all( "~\{func-(.*?)\}~", $string, $matches ) )
    	{
    		return $matches[1];
    	}
    }
    print_r( get_funcs( "Random text {func-test} more random text and then {func-mine}" ) ); 
    ?>
    
    PHP:
     
    krakjoe, Nov 9, 2007 IP
    SniperFox.com likes this.
  7. SniperFox.com

    SniperFox.com Guest

    Messages:
    154
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #7
    @nico_swd and krakjoe Thanks both of your :D Working perfectly now. Thanks :)
     
    SniperFox.com, Nov 9, 2007 IP