dexter dexter - 1 month ago 5
PHP Question

how to replace result urls using regex php

i want to parser web using simple dom ,i get output like here

my code

foreach($html->find('ul[class=result-topic] a ') as $e){
$count++;


$d = ($e->href )."<br>";




echo($d)."<br>";
if($count == 2)
{
exit();
}
}


output

/news/354985850
/film/74808409409


this not full article ,how to replace url with full article like here ,output

/news/full/354985850
/film/full/74808409409

Answer

One way would be to explode, append the second to last element, then implode.

$string = '/news/354985850';
$parts = explode('/', $string);
$parts[(count($parts) - 1)] = 'full/' . $parts[(count($parts) - 1)]; 
echo implode('/', $parts);

Demo: https://eval.in/669122

Another approach would be a regex with preg_replace:

$string = '/news/354985850';
echo preg_replace('~(.*)/~', '$1/full/', $string);

Demo: https://eval.in/669123

Regex Demo: https://regex101.com/r/dQJY8v/1

Comments