PHP captures date text

-2

I have a list with these values:

<li data-breadcrumb="Caixa 1 - Quarto 2 - Casa 3"> Conteúdo </li>

And I would like to reverse their order in PHP.

I made a function

function inverte_breadcrumb($texto){
 $texto = explode(' - ', $texto);
 $texto = array_reverse($texto);
 $texto = implode(' - ', $texto);

 return $texto;
}

And with preg_replace I thought about doing the following:

$novaslinhas = preg_replace("/data-breadcrumb="(.*)"/", 'data-breadcrumb="' . inverte_breadcrumb("$1") . '"', $novaslinhas);

But, it does not call the function.

Does anyone know why?

    
asked by anonymous 02.07.2018 / 06:57

1 answer

0

You will not be able to use preg_replace because it receives value of type string or array with strings in parameter replacement

To get the result, use the preg_replace_callback function to perform a callback.

use:

preg_replace_callback('expressão', 'callback', 'string');

Your code:

$novaslinhas = preg_replace_callback("/data-breadcrumb=\"(.*)\"/",
                                               'inverte_breadcrumb', $novaslinhas);

Note that the function name has been reported as a string, now change the first line of the function, informing the index that in the case is 1:

$texto = explode(' - ', $texto[1]);

Also change the return, because a string must be returned that will be substituted:

return 'data-breadcrumb="'. $texto . '"';

See working at repl.it

Complete code:

function inverte_breadcrumb($texto){
  $texto = explode(' - ', $texto[1]);
  $texto = array_reverse($texto);
  $texto = implode(' - ', $texto);
  return 'data-breadcrumb="'. $texto . '"';
}

$novaslinhas = preg_replace_callback("/data-breadcrumb=\"(.*)\"/", 'inverte_breadcrumb', $novaslinhas);

References:

02.07.2018 / 07:54