Search code examples
phpregexsplitextract

PHP regex, extracting characters between specified characters


I cannot for the life of me seem to be able to figure out how I extract characters between characters.

Consider this string,

  $string = "sometext/#a=10/#b=25/moretext";

What I would like to do is extract the values of "a" and "b" (10 and 25)

So essentially what I want to do is find "#a=" and grab everything before the following /, then do the same for b. Can anyone tell me how this can be accomplished?

Also if anyone knows any solid regex tutorials they can recommend I'd very much appreciate it, I've checked nettuts, w3schools, and php.net which all have good ones but any other recommendations would be great.


Solution

  • This works for me:

    <?php
    
    $string = "sometext/#a=10/#b=25/moretext/#varname=Hello World/evenmoretext/";
    
    $matchcount = preg_match_all('@#([^=]+)=([^/]*)/@', $string, $matches);
    
    for ($i = 0; $i < $matchcount; ++$i) {
        echo "{$matches[1][$i]} = {$matches[2][$i]}\n";
    }
    

    Output:

    a = 10
    b = 25
    varname = Hello World

    A long time ago I found the site http://www.regular-expressions.info/ to be helpful and it had good information. You may find that a GUI program for testing regular expressions can be helpful as they can show matches in real time as you type an expression. An example that comes to mind is Regex Buddy, but this costs money. This online regex tester looked pretty promising as well.