Key
Key

Reputation: 396

PHP regex - replace all text between a tag

I have a link being outputted on my site, what i want to do is replace the visible text that the user sees, but the link will always remain the same.

There will be many different dynamic urls with the text being changed, so all the example regex that i have found so far only use exact tags like '/.*/'...or something similar

Edited for a better example

$link = '<a href='some-dynamic-link'>Text to replace</a>';
$pattern = '/#(<a.*?>).*?(</a>)#/';
$new_text = 'New text';
$new_link = preg_replace($pattern, $new_text, $link);

When printing the output, the following is what i am looking for, against my result.

Desired

<a href='some-dynamic-link'>New text</a>

Actual

'New text'

Upvotes: 3

Views: 4859

Answers (2)

Harsh Patel
Harsh Patel

Reputation: 1334

If you needs to get everything in Between tags then you can use below function

<?php
    function getEverything_inBetween_tags(string $htmlStr, string $tagname)
    {
        $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
        preg_match_all($pattern, $htmlStr, $matches);
        return $matches[1];
    }
    $str = '<a href="test.com">see here for more details about test.com</a>';
    echo getEverything_inBetween_tags($str, 'a');

   //output:- see here for more details about test.com
?>

if you needs to extract HTML Tag & get Array of that tag

<?php 
    function extractHtmlTag_into_array(string $htmlStr, string $tagname)
    {
        preg_match_all("#<\s*?$tagname\b[^>]*>.*?</$tagname\b[^>]*>#s", $htmlStr , $matches);
        return $matches[0];
    }

    $str = '<p>test</p><a href="http://test.com">test.com</a><span>testing string</span>';
    $res = extractHtmlTag_into_array($str, 'a');
    print_r($res);

   //output:- Array([0] => "<a href="https://www.amazon.in/Amazon-Brand-Solimo-liner-brush/dp/B08GLHM9SF?=&amp;src=test.in&amp;=&amp;=">amazon.in/xyz/abc?test=abc</a>") 
?>

Upvotes: 1

nicael
nicael

Reputation: 18995

As you're already using the capture groups, why not actually use them.

$link = "<a href='some-dynamic-link'>Text to replace</a>";
$newText = "Replaced!";
$result = preg_replace('/(<a.*?>).*?(<\/a>)/', '$1'.$newText.'$2', $link);

Upvotes: 9

Related Questions