Find value between square brackets

Discussion in 'PHP' started by papa_face, Jul 27, 2009.

  1. #1
    Hello,

    I am trying to find the value of the text between square brackets in my string

    
    $str = "hell my name is [andrew]";
    $find = preg_split("\[(*])\]", $str, null, 1);
    $name = trim($find[1]);
    
    Code (markup):
    However this is not working :'(

    Anyone got any ideas?
     
    papa_face, Jul 27, 2009 IP
  2. zeronese

    zeronese Peon

    Messages:
    83
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    look at this post

    http://forums.digitalpoint.com/showthread.php?t=1421903

    or use this function

    function get_string_between($string, $start, $end){
            $string = " ".$string; 
           $ini = strpos($string,$start);
            if ($ini == 0) return "";
            $ini += strlen($start);
             $len = strpos($string,$end,$ini) - $ini;
            return substr($string,$ini,$len);
    }
    
    $str = "hell my name is [andrew]";
    echo get_string_between($str, "[", "]");
    PHP:
     
    zeronese, Jul 27, 2009 IP
  3. gustavorg

    gustavorg Active Member

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #3
    This could be resolved using regular expressions, we dont need to use dump coder technnics here. You should use preg_match, is more easy that way:

    $str = "hell my name is [andrew]";
    preg_match("/^(.*\[)(.*)(\])/", $str, $find);
    $name = trim($find[2]);
    Code (markup):
    You should add validations, for example to handle when the string doesnt have any [].

    I hope this helps.

    Gustavo
     
    gustavorg, Jul 27, 2009 IP
  4. papa_face

    papa_face Notable Member

    Messages:
    2,237
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    285
    #4
    Thanks, that did it :)
     
    papa_face, Jul 28, 2009 IP