Skip to content
Advertisement

Replacing part of string with prefix and suffix

$str = ' I love [123] and [124] at (456). I hate [234] and [235] at (123).'

I want to make it

$str = 'I love <a title="a">[123]</a> and <a title="b">[124]</a> at <a title="XX">(456)</a>. I hate <a title="c">[234]</a> and <a title="d">[235]</a> at <a title="ZZ">(123)</a>.'

Texts to replace with is with in braces () or [] and can be found from Table 1 or Table 2.

Table 1
123 | a
124 | b
234 | c
235 | d

Table 2
456 | XX
123 | ZZ

Current approach

$text=explode(' ', $text);
for ($i=0; $i<count($text); $i++) {
    for ($j=0; $j<count($table1Col1); $j++) {
        if ($text[$i] == $table1Col1[$j])
            $text[$i] = '<a href="#" title="'.$table1Col2[$j].'">'.$table1Col1[$j].'</a>';
    }
    for ($j=0; $j<count($table2Col1); $j++) {
        if ($text[$i] == $table2Col1[$j])
            $text[$i] = '<a href="#" title="'.$table2Col2[$j].'">'.$table2Col1[$j].'</a>';
    }
}

How to improve the code to skip not-required loop ?

Advertisement

Answer

There may be a way with one loop that I’ll think on, but since the arrays have the same keys they can’t be merged:

foreach($table1Col1 as $find => $repl) {
    $text = str_replace("[$find]",
                        "<a title="$repl">[$find]</a>",
                        $text);
}

foreach($table1Col2 as $find => $repl) {
    $text = str_replace("($find)",
                        "<a title="$repl">($find)</a>",
                        $text);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement