Php “如何替换”+&引用;至Ӯ&引用;及=&引用;至ӯ&引用;在我的文本中?
如果右或左此符号有字母,如何将“+”替换为“Ӯ”,将“=”替换为“ӯ”?我使用str_replace(),但它会替换所有符号。我的文本:Php “如何替换”+&引用;至Ӯ&引用;及=&引用;至ӯ&引用;在我的文本中?,php,regex,replace,preg-replace,cyrillic,Php,Regex,Replace,Preg Replace,Cyrillic,如果右或左此符号有字母,如何将“+”替换为“Ӯ”,将“=”替换为“ӯ”?我使用str_replace(),但它会替换所有符号。我的文本: $str = "+ро ба касе = намебахшид. + метавонист мавз=и =ро гирад. 2+1=3 ва 3 = 2 + 1" 我必须得到这样的结果: 。Ӯ метавонист мавзӯи ӯро гирад. 2+1=3а3=2+1 当我使用str\u replace()时,我得到的结果是: str_repla
$str = "+ро ба касе = намебахшид. + метавонист мавз=и =ро гирад. 2+1=3 ва 3 = 2 + 1"
我必须得到这样的结果:
。Ӯ метавонист мавзӯи ӯро гирад. 2+1=3а3=2+1
当我使用str\u replace()
时,我得到的结果是:
str_replace(array("+","="), array("Ӯ", "ӯ"), $str);
。Ӯ метавонист мавзӯи ӯро гирад. 2Ӯ1ӯ3ӯ2Ӯ1使用unicode属性编辑:
$str = "+ро ба касе = намебахшид. + = метавонист мавз=и =ро = гирад. 2+0=3 ва 3 = 2 + -1=+";
$str = preg_replace(array('/\+(?=\s*+[+=]?\s*\p{L})/','/=(?=\s*+[+=]?\s*\p{L})/'), array('Ӯ','ӯ'), $str);
echo $str,"\n";
(?= : lookahead, make sure we have after the sign + or =
\s*+ : 0 or more spaces, the most we can find
[+=]? : + or =, optional
\s* : 0 or more spaces, not greedy
\p{L} : a letter in any language
) : end lookahead
Ӯро ба касе ӯ намебахшид. Ӯ ӯ метавонист мавзӯи ӯро ӯ гирад. 2+0=3 ва 3 = 2 + -1=+
说明:
$str = "+ро ба касе = намебахшид. + = метавонист мавз=и =ро = гирад. 2+0=3 ва 3 = 2 + -1=+";
$str = preg_replace(array('/\+(?=\s*+[+=]?\s*\p{L})/','/=(?=\s*+[+=]?\s*\p{L})/'), array('Ӯ','ӯ'), $str);
echo $str,"\n";
(?= : lookahead, make sure we have after the sign + or =
\s*+ : 0 or more spaces, the most we can find
[+=]? : + or =, optional
\s* : 0 or more spaces, not greedy
\p{L} : a letter in any language
) : end lookahead
Ӯро ба касе ӯ намебахшид. Ӯ ӯ метавонист мавзӯи ӯро ӯ гирад. 2+0=3 ва 3 = 2 + -1=+
输出:
$str = "+ро ба касе = намебахшид. + = метавонист мавз=и =ро = гирад. 2+0=3 ва 3 = 2 + -1=+";
$str = preg_replace(array('/\+(?=\s*+[+=]?\s*\p{L})/','/=(?=\s*+[+=]?\s*\p{L})/'), array('Ӯ','ӯ'), $str);
echo $str,"\n";
(?= : lookahead, make sure we have after the sign + or =
\s*+ : 0 or more spaces, the most we can find
[+=]? : + or =, optional
\s* : 0 or more spaces, not greedy
\p{L} : a letter in any language
) : end lookahead
Ӯро ба касе ӯ намебахшид. Ӯ ӯ метавонист мавзӯи ӯро ӯ гирад. 2+0=3 ва 3 = 2 + -1=+
我将使用
preg\u replace\u callback
执行此操作:
$corr = ['+' => 'Ӯ', '=' => 'ӯ'];
$str = preg_replace_callback('~(?:[+=]\s*)+(?=\pL)|\pL\s*\K(?:[+=]\s*)+~u', function ($m) use ($corr) {
return strtr($m[0], $corr);
}, $str);
是,
str\u replace
将替换所有发生的事件。您需要使用类似于preg_replace
的工具来执行更复杂的字符串替换|(?这是解决这个问题的最佳方法吗?或者你仍然可以优化大文本的代码?@TotoYou当我的文本:+crmk_аааааааа=аа=аааааааааааааааа“ӯааааааааааааааааааааааааааааааааааа1072(我会将所有内容添加到正则表达式中是吗?@Otabek:是的,但是很难区分+=МааааСа
和2 1+=3
。最好的方法是编写一个解析器。感谢您的帮助!@Casimir et Hippolyte。但是您的代码替换“+1”
到“1”
的输出必须是“+1”“@Otabek:你的意思是只在两边都有字母的情况下才替换吗?数字也可以是空格、逗号和符号,它们将出现在句子的末尾“Мааааааааааааааа=5ааааааааа
但您的代码仍然更接近解决方案…@Casimir etHippolyte@Otabek:不确定。你应该用更多的例子和更清楚的解释来编辑你的问题。