Hi, I want to extract text from a site between certain tags, If the tags are in the foolowing format: <a class="classname" target="_blank"> This Text</a><span class="classname"> HTML: How can i use php to loop through and collect "This Text" Thanks
preg_match_all('~<a class="classname" target="_blank">([^<]+)</a>~i', $text, $matches); print_r($matches[1]); PHP:
I tried my code with this as source text, and it worked for me: $text = '<a class="classname" target="_blank"> This Text</a><span class="classname"> <a class="classname" target="_blank"> This Text</a><span class="classname"> <a class="classname" target="_blank"> This Text</a><span class="classname">'; preg_match_all('~<a class="classname" target="_blank">([^<]+)</a>~i', $text, $matches); print_r($matches[1]); PHP: Output: Array ( [0] => This Text [1] => This Text [2] => This Text ) Code (markup): Does $text contain the source code?
I think so .. If i wanted it to start with: class="classname" and not <a class="classname" would this be correct? $html = file_get_contents('url here'); preg_match_all('~class="classname" target="_blank">([^<]+)</a>~i', $html, $matches); print_r($matches[1]); Code (markup):
How can i get it echo just the values so instead of: Array ( [0] => This Text [1] => This Text [2] => This Text ) It would output: This Text This Text This Text
echo $matches[1][0]; echo $matches[1][1]; echo $matches[1][2]; // and so on. PHP: You can also make a shortcut: $matches = $matches[1]; echo $matches[0]; echo $matches[1]; // ... PHP: ... and remove the print_r() line.
Well you could loop through them: foreach ($matches[1] AS $match) { echo $match, '<br />'; } PHP: Or: echo implode(', ', $matches[1]); PHP: Depends on how you want to display them...