Search code examples
phpregexpreg-replacedomdocumentstr-replace

Replacing inside body using PHP


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.


Solution

    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;