PHP captures date text

Asked

Viewed 50 times

-2

I have a list of those values:

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

And I’d like to reverse their order in PHP.

I did a function

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

 return $texto;
}

and with the preg_replace thought to do the following:

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

But, it does not call the function.

Does anyone know why?

  • 1

    first, you are making a mess by delimiting the string with double quotes and at the same time using double quotes without escape. Second, you try to apply a function with the value "$1", it will even be called yes, but it is without effect (it will not reverse anything, because "$1" has no strokes. Put a print_r($texto) inside the inverte_breadcrumb function you will see that it will be called (after you fix the quotes). I hope that at these times of the comment you have already noticed that the function "reverses" will be called before replace, that is, it will not have the effect that you intend.

1 answer

0


It will not be possible using the function preg_replace because it takes value of the string or array type with strings in the parameter replacement

To get the result, use the function preg_replace_callback run 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 was entered as a string, now change the first line of the function, stating the index which in case is 1:

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

also change the return, because a string must be returned that will be a substitute:

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

See working on 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:

  • Perfect guy, I know I have a lot to learn yet, but thanks for the help!!!

Browser other questions tagged

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