[英]PHP - Check if string contains words longer than 4 characters, then include "+ *", and for those shorter than 4 characters include only "*"
我设法只做一部分,但不能让第二部分工作。
<
4 个字符,则只应在该词的末尾包含*
。>=
4 个字符,则应在末尾添加*
,并在开头添加+
。我做的代码...
$string = "This is a short sentence which should include all regex results";
preg_match_all('/\b[A-Za-z0-9]{4,99}\b/', $string, $result);
echo implode("* +", $result[0]);
将产生以下结果......
This* +short* +sentence* +which* +should* +include* +regex* +results
虽然它应该返回以下结果......
+This* is* a* +short* +sentence* +which* +should* +include* all* +regex* +results*
PS:我希望这可以提高对 innodb 表进行全文搜索的灵活性。
您可以使用preg_replace
和两个正则表达式进行替换,一个匹配具有 1-3 个字母的单词,一个匹配具有 4 个或更多字母的单词:
$string = "This is a short sentence which should include all regex results";
echo preg_replace(array('/\b(\w{1,3})\b/', '/\b(\w{4,})\b/'), array('$1*', '+$1*'), $string);
Output:
+This* is* a* +short* +sentence* +which* +should* +include* all* +regex* +results*
这个正则表达式任务可以通过输入字符串一次完成。
代码:(演示)
$string = "This is a short sentence which should include all regex results";
echo preg_replace_callback(
'~(\w{3})?(\w+)~',
fn($m) => ($m[1] ? "+" : '') . "$m[0]*",
$string
);
Output:
+This* is* a* +short* +sentence* +which* +should* +include* all* +regex* +results*
该模式可选择匹配每个“单词”的前三个单词字符——纯粹是为了确定是否应在替换前添加一个加号。 第二个捕获组未在替换中使用,但声明它以确保第一个捕获组始终存在(以便避免迭代 `isset() 调用)。 然后只需使用完整的字符串匹配和 append 一个星号即可完成替换字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.