CommanderSpock CommanderSpock - 1 year ago 41
PHP Question

higlight whole word if first 3 chars are valid

I got some function (part of):

foreach ($keyword as $key) {
$keyword = substr($key, 0, 3);
$para = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<span style='color:#20a8d8'>$1</span>",$para);
}


and now I can highlight results of my foreach loop, of course only first 3 chars, how can i highlight whole word where 3 first chars are valid ?

I tried also:

foreach ($paras as $para) {
$keyword = explode(" ", $keyword);

foreach ($keyword as $key) {
$keywordcheck = substr($key, 0, 3);
$paracheck = preg_replace("/\b([a-z]*${keywordcheck}[a-z]*)\b/i","<span style='color:#20a8d8'>$1</span>",$para);
if (isset($paracheck)) {
$para = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<span style='color:#20a8d8'>$1</span>",$para);
}
}
}


new code:

foreach ($paras as $para) {
$keyword = explode(" ", $keyword);

foreach ($keyword as $key) {
$key = substr($key, 0, 3);
$para = preg_replace("/\b({$key}[a-z]*)\b/i","<span style='color:#20a8d8'>$1</span>", $para);
}

echo '<tr><td style="width:15%"></td>';
echo '<td>';
echo 'META TITLE: '.$para.'';
echo '</td></tr>';
}

Answer Source

Try this

$para = "Microsoft is company placed in USA";
$keyword = ['com'];

foreach ($keyword as $key) {
    $kw = substr($key, 0, 3);
    $para = preg_replace("/\b({$kw}[-a-z]*)\b/i","<span style='color:#20a8d8'>$1</span>", $para);
}

echo $para;

http://ideone.com/rGb5q8

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download