Home > Mobile >  Replacing inside body using PHP
Replacing inside body using PHP

Time:01-27

i am trying to replace inside body tag using PHP but every time i am getting different output than i expecting the one.

Try :

$homepage = "<head>https://www.example.com</head> <body>https://www.example.com</body>";
$homepage = substr($homepage, strpos($homepage, "<body>"));
$homepage = preg_replace("/https:\/\/(.?) \.example\.com/", "https://www.example.net", $homepage);
echo $homepage;

Output :

<head>https://www.example.net</body>

The output i am looking for :

<head>https://www.example.com</head> <body>https://www.example.net</body>

I just want to change/replace the string inside tag.

CodePudding user response:

  1. Split head & body
  2. Replace string in body
  3. Join head & body

Your regex was problematic, I assumed you wanted to catch both https://www.example.com and https://example.com

Here is what you are looking for:

<?php

$homepage = '<head><link rel="stylesheet" type="text/css" href="https://www.example.com/whatever.css"></head><body>This link <a href="https://www.example.com">https://example.com</a> and this one <a href="https://www.example.com">https://www.example.com</a> will be replaced</body>';

$neck_pos = strpos($homepage, "<body");
$head = substr($homepage, 0, $neck_pos);
$body = substr($homepage, $neck_pos);


$body = preg_replace("/https:\/\/[w]*\.*example\.com/", "https://www.example.net", $body);

$homepage = $head . $body;

echo $homepage;

CodePudding user response:

Well, to reiterate what you were told in the comments: don't use regex on HTML/XML - ever. Always use a parser and (preferably) xpath to do the search. Look at the example below as a first step - you WILL need to read up on the whole subject. If the HTML/XML gets more complicated, so will the search:

$homepage = "<head>https://www.example.com</head> <body>https://www.example.com</body>";
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($homepage, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($doc); 
$target= $xpath->query('//body');
$target[0]->nodeValue="https://www.example.net";
echo $doc->saveHTML();

Output:

<p>https://www.example.com <body>https://www.example.net</body></p>
  •  Tags:  
  • Related