-2

I'm trying to insert an element with str_replace (), counting the number of paragraphs in the content, for example:

<?php
$result_information = "<p>parrafo 1</p>  <p>parrafo 2</p> <p>parrafo 3</p>";
$result_information1 = str_replace("<p>[1]", "<p>cambio", $result_information);
echo $result_information1;
?>

I try to use <p>[1] , unfortunately it doesn't work for me, any way to get the first paragraph and replace it?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • There are a lot of ways to do this, but I think you either need to explode to an array on `

    ` or use an html parsing library to identify and replace the portions you need. You could also hack something together with this one: https://stackoverflow.com/questions/5696412/how-to-get-a-substring-between-two-strings-in-php + `str_replace()`

    – TCooper Dec 06 '19 at 20:09

2 Answers2

2

It would create an array from $result_information with preg_split() and then replace the first element of the array.

<?php
$result_information = "<p>parrafo 1</p>  <p>parrafo 2</p> <p>parrafo 3</p> <p>parrafo 4</p>";
$result_information = preg_replace("/<\/p>(.*?)<p>/", "<p></p>", $result_information); # remove spaces
$array = preg_split("/<p>(.*?)<\/p>/", $result_information, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$array[0] = "cambio";
$array[2] = "cambio";
$result_information1 = "<p>" . implode($array, "</p><p>"). "</p>";
echo $result_information1;
?>
Tux
  • 121
  • 1
  • 2
  • 9
0

IMHO it would be best to deal with this using DOMDocument. As always this is more complicated than using replace/regexes - but usually it's worth the effort as it handles the content as HTML rather than just plain text.

The main code for being able to process document fragments is heavily based on https://stackoverflow.com/a/29499398/1213708, all I have done is added the ability to refer to the paragraphs as you are after.

The p tags part is just the

$pTags = $doc->getElementsByTagName("p");
$pTags[1]->textContent = "cambio";

so first is to get a list of the p tags - you now have an array which you can set as in the second line of code.

$result_information = "<p>parrafo 1</p>  <p>parrafo 2</p> <p>parrafo 3</p>";

$doc = new DOMDocument();
$doc->loadHTML("<div>$result_information</div>");
$pTags = $doc->getElementsByTagName("p");
$pTags[1]->textContent = "cambio";

$container = $doc->getElementsByTagName('div')->item(0);
$container = $container->parentNode->removeChild($container);
while ($doc->firstChild) {
    $doc->removeChild($doc->firstChild);
}

while ($container->firstChild ) {
    $doc->appendChild($container->firstChild);
}
echo $doc->saveHTML();
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55