我有一些功能(部分):
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);
}
现在我可以突出我的foreach循环的结果,当然只有前3个字符,我怎样才能突出显示3个第一个字符有效的整个单词?
我也试过了:
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);
}
}
}
新代码:
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>';
}
答案 0 :(得分:1)
试试这个
$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;
答案 1 :(得分:0)
你可以爆炸字符串并使用Substr来检查foreach中每个单词的前三个 我使用str_replace将单词替换为span标记中包含的单词。
<Window x:Class="WPFCustomeControlLibrary.Window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Window" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary Source="Dictionary.xaml" />
</Window.Resources>
<Grid DataContext="{Binding MainViewModel, Mode=OneWay, Source={StaticResource Locator}}">
</Grid>
</Window>
在我看来,没有理由使用正则表达式,因为它不是真正的模式。这只是前三个角色。
修改以确保它不会突出显示人物中的 $str = "a life with fitness is boring but it may fit some people. Apples new iFit is not highlighted";
$arr = explode(" ", $str);
Foreach($arr as &$word){
If(Substr($word,0,3) == "peo"){
// If word has a . Or any other special character after the word handle it.
If(ctype_alpha(Substr($word,-1))){
$word = str_replace($word, "<span style='color:#20a8d8'>".$word."</span>", $word);
}Else{
$char = substr($word,-1); //if it has a dot this "saves" it
// Here I remove the dot, and insert it last (after span)
$word = str_replace($word, "<span style='color:#20a8d8'>".substr($word,0,-1)."</span>", $word) . $char;
}
}
}
Echo implode(" ", $arr);
。