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
Share on other sites

thanks, however it doesn't seem to work properly.

 

I did the following to print the results to test: print_r($match);

 

and i get:

Array ( [0] => Array ( ) [1] => Array ( ) )

 

an array with 2 arrays in? i'm after an array of strings. Any idea whats happening?

Link to comment
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.