Jump to content

regex string extract


jk11uk

Recommended Posts

hi, i want to extract strings from a page which are in the following format:

<span class=a>STRING</span>

 

so all different substrings from within the main string which start with <span class=a> and end with </span> would be captured.

 

I came up with the following which doesn't seem to work at all :(

 

 

preg_match_all('"^(<span class=a>)(</span>)$"', $mainstring, $match);

 

//// print results to test

 

echo $match[1];

 

 

any ideas?

Link to comment
https://forums.phpfreaks.com/topic/94526-regex-string-extract/
Share on other sites

The array created by preb_match_all(), $match, in this case is a multidimensional array.

 

preg_match_all() Documentation

http://us2.php.net/manual/en/function.preg-match-all.php

 

 

In this example...

<?php

$mainstring = "<span class=a>A</span><span class=a>B</span><span class=a>C</span>";
preg_match_all('"<span class=a>(.+?)</span>"', $mainstring, $match);
print_r($match);

?>

 

you would get output that looks like:

Array
(
    [0] => Array
        (
            [0] => <span class=a>A</span>
            [1] => <span class=a>B</span>
            [2] => <span class=a>C</span>
        )

    [1] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

)

The array you are after is actually $matches[1];

 

To use those strings you could do something like:

<?php
echo "I found: ", implode(", ", $matches[1]), "\n";
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/94526-regex-string-extract/#findComment-484865
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.