سؤال

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?

هل كانت مفيدة؟

المحلول

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));

Output:

<span class="vmshipment_name">Fragtmand</span>

نصائح أخرى

Depends on what other use cases you have. For the simple example you've given, I would use a regular expression. For a more general class of use cases, you will probably want to use a DOM parser, like PHP DOM.

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>
        )

)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top