Results 1 to 3 of 3

Thread: [RESOLVED] Help parse string

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    From the UK
    Posts
    422

    Resolved [RESOLVED] Help parse string

    $description = ' "klsfdsfasdfasdf" slsjfklasdf "kjsfklasdjflaksfja" ';

    What I would like to do is to finish off with a string of only the first group of brackets. So everything after that is to be discarded.

    I can use 'substr' to begin from the 1st letter (not the 0th as that is the first ") but how can I make it continue on until the NEXT "?

    eg.

    $d = substr($description,1,?);

  2. #2
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: Help parse string

    Actually, because you have whitespace at the start of the string, the character at position 1 is ", because position 0 is the whitespace. So the first thing you'd want to do is trim(), and then you could use substr() with the help of strpos(), like so:

    Code:
    $description = trim($description);
    $d = substr($description,1,strpos($description,'"',1)-1);
    strpos($description,'"',1)-1 will return the position of the second ", minus one, which is the length of the sub string you want.

    I tend to prefer regex for string parsing though - it's usually simpler and more powerful. Using preg_match(), you'd do this:

    Code:
    preg_match('/"([^"]*)"/',$description,$matches);
    Your matched string is now is $matches[1] ($matches[0] contains the string too, but with " on either side). I can explain this example in more detail if you'd like.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2006
    Location
    From the UK
    Posts
    422

    Re: Help parse string

    Excellent, thank you! I used the preg_match method and it worked great

Posting Permissions

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



Click Here to Expand Forum to Full Width