Replace starting at x and ending at y in php

Asked

Viewed 33 times

1

I have the following html code:

<a title="Link 01" href="http://www.meusite.com.br/?id=121451781">Link 01</a>
<a title="Link 10" href="http://www.meusite.com.br/?id=13456712">Link 10</a>

I need a replacement that starts at ?id= and end in ">. replace would be about that: $path = str_replace("1","*",$texto);

But if I leave just replace it, it will also replace the name "Link 01" leaving it as "Link 0*" and I don’t want that, I need the replacement only in the "1" of the id. Example of how I want it to stay: <a title="Link 01" href="http://www.meusite.com.br/?id=*2*45*78*">Link 01</a>

From now on, thank you.

2 answers

0

It is not possible to solve this problem with just one step. Below I created a code that solves your problem.


$str1 = "&lta title='Link 01' href='http://www.meusite.com.br/?id=121451781'>Link 01</a>";
$str2 = '&lta title="Link 10" href="http://www.meusite.com.br/?id=13456712">Link 10</a>';

echo changeId($str1);
echo changeId($str2);

function changeId($str)
{

    $explode1 = explode("=", $str); //Separa $str em duas partes à esquerda e à direita de '='
    $explode2 = explode(">", $explode1[3]); //Separa novamente agora à esquerda e à direita de todos os simbolos '>'

    $strQueQueremos = $explode2[0]; //O valor deve ser 121451781" ou 13456712", que são os números que desejamos modificar

    $strModificada = str_replace("1", "*", $strQueQueremos);

    $strFinal = str_replace($strQueQueremos, $strModificada, $str);

    return $strFinal;
}

0

You can do it this way:

<?php
function capturar($string, $start, $end) {
   global $url;
   $str = explode($start, $string);

   if(isset($str[1])){
      $str = explode($end, $str[1]);
      $string = str_replace($start.$str[0].$end,'',$string);
      $str2 = str_replace('1','*',$str[0]);
      $url = str_replace($str[0],$str2,$url);
      capturar($string, $start, $end);
    }
}
$url = '
<a title="Link 01" href="http://www.meusite.com.br/?id=121451781">Link 01</a>
<a title="Link 10" href="http://www.meusite.com.br/?id=13456712">Link 10</a>
';

capturar($url, 'id=', '">');

echo $url;
// saída:
// $url = '<a title="Link 01" href="http://www.meusite.com.br/?id=*2*45*78*">Link 01</a>
// <a title="Link 10" href="http://www.meusite.com.br/?id=*34567*2">Link 10</a>'

?>
  • http://sandbox.onlinephpfunctions.com/code/2041d6d0d3ee3ef8f2a699613f3021aebe82b1f1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.