简体   繁体   English

如何小写字符串 php 中的特定单词

[英]How to lowercase a specific word in a string php

Hye Guys !!嘿伙计们!!

I need your help: Here are 2 elements:我需要你的帮助:这里有 2 个要素:

$string = "Legend Of Zelda";
$array = array("to","of","at");

I'd like to check if $string contains one of the $array elements and lowercase it.我想检查 $string 是否包含 $array 元素之一并将其小写。 Tried this, but failed... i got the felling that the first element of the preg_replace should be a pattern or so?试过这个,但失败了......我觉得 preg_replace 的第一个元素应该是一个模式左右?

echo preg_replace($array, mb_strtolower($array), $string);

Any idea?任何想法? Thanks a lot from France !非常感谢法国!

Use preg_replace_callback :使用preg_replace_callback

$string = "Legend Of Zelda";
$array = array("to","of","at");
echo preg_replace_callback('~\b(?:' . implode("|", $array) . ')\b~ui', function ($m) {
    return mb_strtolower($m[0]);
  }, $string);

See PHP demo .请参阅PHP 演示

The regex will look like \b(?:to|of|at)\b here, see its demo online .正则表达式在这里看起来像\b(?:to|of|at)\b ,请参阅它的在线演示

The /i flag will ensure case insensitive search and /u will handle all Unicode chars correctly. /i标志将确保不区分大小写的搜索,并且/u将正确处理所有 Unicode 字符。

Maybe this can help you:也许这可以帮助你:

$content = "Legend Of Zelda";
$array = array("to","of","at");

foreach($array as $value)
{
    $pattern = '/'.$value.'/i';
    $content = preg_replace($pattern, strtolower($value) , $content);
}


echo $content;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM