Reputation: 499
I´m looking for a PHP solution to strip the content of a string except a specific HTML element and its content.
Here is an example:
Original string
<span class="vmshipment_name">Fragtmand</span>
<span class="vmshipment_description">Vi leverer i hele landet. Alle produkter fra Jabo, herunder hytter, havehegn osv. transporteres fra Sverige.<br>
Leveringstiden er ca. 12-18 dage.</span>
Now, this is what I want to extract
<span class="vmshipment_name">Fragtmand</span>
So, Im looking for a PHP expression to strip/remove everything in a string except the span-element with class name "vmshipment_name"
Does anyone know a way to do this?
Upvotes: 0
Views: 122
Reputation: 41
Please note that you should be escaping and sanitizing your inputs.
You can also use preg_match instead, if you only want to match one. The below code matches them all.
<?php
$test_string = '<span class="vmshipment_name">Fragtmand</span>
<span class="vmshipment_description">Vi leverer i hele landet. Alle produkter fra Jabo, herunder hytter, havehegn osv. transporteres fra Sverige.<br>
Leveringstiden er ca. 12-18 dage.</span>';
preg_match_all('@<span.+class="vmshipment_name".+</span>@', $test_string, $matches);
print_r($matches);
?>
Output:
Array
(
[0] => Array
(
[0] => <span class="vmshipment_name">Fragtmand</span>
)
)
Upvotes: 0
Reputation: 10975
Please try the DomDocument class:
<?php
$html = '<span class="vmshipment_name">Fragtmand</span>
<span class="vmshipment_description">Vi leverer i hele landet. Alle produkter fra Jabo, herunder hytter, havehegn osv. transporteres fra Sverige.<br>
Leveringstiden er ca. 12-18 dage.</span>';
$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$results = $xpath->query("//*[@class='vmshipment_name']");
echo $dom->saveHTML($results->item(0));
<span class="vmshipment_name">Fragtmand</span>
Upvotes: 1