0

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.

Glavić
  • 42,781
  • 13
  • 77
  • 107
Jajaja
  • 133
  • 1
  • 10

2 Answers2

1

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

Glavić
  • 42,781
  • 13
  • 77
  • 107
  • Caution should be taken that DOM approach will lose other HTML tags like `` between `` and ``. – Phil Jan 26 '18 at 11:32
  • @Phil: it depends what does OP need. He can still get whole HTML of that link with this command in the loop: `$dom->saveXML($link)` and then parse that further... – Glavić Jan 27 '18 at 19:25
1

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);
Phil
  • 1,444
  • 2
  • 10
  • 21
  • But How I can in foreach paste $matches[1][0] ? – Jajaja Jan 26 '18 at 12:48
  • Thanks. I have 1 question. How I can replace `$body` with founded matches? Example: I want replace `site.com/text/some` on `site.com/some?id=32324` in text. How I can do it? – Jajaja Jan 26 '18 at 13:12
  • If you already know the old string, your'd better replace it directly using `str_replace`. If you don't know the exact old string, you could use `preg_replace` to find and replace the old string with the new one. However, you have to know the pattern of how to find the older string. – Phil Jan 26 '18 at 13:22
  • Updated. Hope it helps. – Phil Jan 26 '18 at 14:03
  • Do not parse HTML with regex: https://stackoverflow.com/a/1732454/67332 – Glavić Jan 27 '18 at 19:27