1

I want to replace a certain word in a text string which contains HTML characters. So that's this word turn into a link.

So, for example when I get this String

    Text I get: Lorem ipsum dolor sit amet

I want it to be like this

    Result: Lorem <a href="url">ipsum</a> dolor sit amet

I already archive this with function at the end.

But if the String I get already has the link

    Text I get: Lorem <a href="url">ipsum</a> dolor sit amet

it becomes like this

    Result: Lorem <a href="url"></a> <a href="url">ipsum</a> dolor sit amet

My Function look like this.

function replaceStrings($string) {

$arrCounter = 0;
$arrString = array();

if( have_rows('options_links_repeater', 'option') ):
    while( have_rows('options_links_repeater', 'option') ): the_row();
        $replacetext = get_sub_field('options_links_repeater_text', 'option');
        $replacelink = get_sub_field('options_links_repeater_links', 'option');
        $arrString[$arrCounter]["text"] = $replacetext;
        $arrString[$arrCounter]["link"] = $replacelink;
        $arrCounter++;
    endwhile;
endif;

$length = count($arrString);

for ($i = 0; $i < $length; $i++) {

    $searchString = $arrString[$i]["text"];

    $url = $arrString[$i]["link"];
    $urlLink = $arrString[$i]["link"]['url'];
    $urlLinkText = $arrString[$i]["link"]['title'];
    $urlLinkTarget = $arrString[$i]["link"]['target'] ? $arrString[$i]["link"]['target'] : '_self';


    $string = preg_replace('/'.$searchString.'\b/', '<a href="'.$urlLink.'" target="'.$urlLinkTarget.'">'.$searchString.'</a>', $string);
}

echo $string;

  }

I think the only part that matters now, is the preg_replace.

Can you help me to solve this issue. So that's the word is not replaced if the word is already a link.

Edit: Thank you for the link @bobble-bubble. The accepted answer in this thread helped me: preg_replace to exclude <a href='''></a> PHP

This preg_replace works for me now

    $string = preg_replace("~<a[^>]*>.*?</a\s*>(*SKIP)(*FAIL)|\b".$searchString."\b~", '<a href="'.$urlLink.'" target="'.$urlLinkTarget.'">'.$searchString.'</a>', $string);
enky
  • 40
  • 8

1 Answers1

0

You can use negative look behind, Demo

echo preg_replace('/(?<!>)(ipsum)/',"<a href='url'>$1</a>",$string).PHP_EOL;
LF00
  • 27,015
  • 29
  • 156
  • 295