Jajaja
Jajaja

Reputation: 133

Find string in text and explode

I have a text:

$body = 'I lorem ipsum. And I have more text, I want explode this and search link: <a href="site.com/text/some">I link</a>.';

How can I find "I link" and explode href?

My code is:

if (strpos($body, 'site.com/') !== false) {
    $itemL = explode('/', $body);
}

But this not working.

Upvotes: 0

Views: 141

Answers (2)

Phil
Phil

Reputation: 1464

RegEx is good choice here. Try:

$body = 'I lorem ipsum. And I have more text, I want explode this 
and search link: <a href="site.com/text/some">I link</a>.';

$reg_str='/<a href="(.*?)">(.*?)<\/a>/';

preg_match_all($reg_str, $body, $matches);
echo $matches[1][0]."<br>";   //site.com/text/some
echo $matches[2][0];    //I link

Update

If you have a long text including many hrefs and many link text like I link, you could use for loop to output them, using code like:

for($i=0; $i<count($matches[1]);$i++){
   echo $matches[1][$i]; // echo all the hrefs
}

for($i=0; $i<count($matches[2]);$i++){
   echo $matches[2][$i]; // echo all the link texts.
}

If you want to replace the old href (e.g. site.com/text/some) with the new one (e.g. site.com/some?id=32324), you could try preg_replace like:

echo preg_replace('/<a(.*)href="(site.com\/text\/some)"(.*)>/','<a$1href="site.com/some?id=32324"$3>',$body);

Upvotes: 1

Glavić
Glavić

Reputation: 43572

You could use DOM to operate through your html:

$dom = new DOMDocument;
$dom->loadHTML($body);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//a') as $link) {
    var_dump($link->textContent);
    var_dump($link->getAttribute('href'));
}

demo

Upvotes: 1

Related Questions