0

I would like to get the urls from a webpage that starts with "../category/" from these tags below:

<a href="../category/product/pc.html" target="_blank">PC</a><br>
<a href="../category/product/carpet.html" target="_blank">Carpet</a><br>

Any suggestion would be very much appreciated.

Thanks!

0

2 Answers 2

5

No regular expressions is required. A simple XPath query with DOM will suffice:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodes = $xpath->query('//a[starts-with(@href, "../category/")]');
foreach ($nodes as $node) {
    echo $node->nodeValue.' = '.$node->getAttribute('href').PHP_EOL;
}

Will print:

PC = ../category/product/pc.html
Carpet = ../category/product/carpet.html
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for asking but I haven't used this before and I would like to get the contents from the link. Something like "example.com/p/carpet.html". How will I add this to the code?
@user704278: If you want to rewrite the URL, just do: $new_href = 'example.com/p/'.basename($node->getAttribute('href'));
0

This regex searches for your ../category/ string:

preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches);

All text literals are used for matching. You can replace the ..... to make it more specific. Only the \. need escaping. The .*? looks for a variable length string. And () captures the matched path name, so it appears in $matches. The manual explains the rest of the syntax. http://www.php.net/manual/en/book.pcre.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.