来自MySql邻近搜索的PHP字符串突出显示

问题描述

我想突出显示此查询找到的文本部分:

示例1:

SELECT * FROM myTable WHERE columnA regexp 'work.{0,10}john.{0,10}smith'

要点:“过去五年来我一直为约翰·乔·史密斯(John Joe Smith)工作”

示例2:

SELECT * FROM myTable WHERE columnA regexp 'jo.{0,10}ba.{0,10}tur'

要点:“过去5年来,我一直为 Joseph Balsora Turgeon 工作”

我需要找到字符串中突出显示的开始位置,我可以弄清楚结束没有问题。

即使经过一番研究,我也一无所知。

谢谢, 安迪

解决方法

只需在php中应用相同的正则表达式即可。例如:

<?php 
  $str = "I have been working for John Joe Smith for the last 5 years";
  // Assuming you get the $str from the database

  $highlighted = preg_replace('/work.{0,10}john.{0,10}smith/iu','<b>\0</b>',$str);

  print $highlighted;
  // I have been <b>working for John Joe Smith</b> for the last 5 years

请注意,您需要将正则表达式括在一对符号中(例如上例中的/ ... /)。最后是修饰符。 i允许执行不区分大小写的匹配,u允许使用Unicode字符串/

UPD

也许您也可以直接在MySQL中执行相同的替换:

select REGEXP_REPLACE('I have been working for John Joe Smith for the last 5 years','work.{0,10}smith','<b>\\0</b>') ...
,

我假设您将在HTML端显示为粗体,因此您不必在DB端运行regexp,您可以在PHP上应用:

<?php
$string ="I have been working for John Joe Smith for the last <number> years";
$highlighted = preg_replace("/(working for .*)(for)/",'<b>\1</b> for',$string);

print $highlighted;
// I have been <b>working for John Joe Smith</b> for the last <number> years
?>

想法是找到并分组“为*工作”,然后将它们分为“为*工作”和“为”两个组,然后仅替换第一个组。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...