如何将符号替换为字母

时间:2017-10-08 09:25:30

标签: php regex string replace preg-replace-callback

我的示例文字:

$text = "I've got a many web APP=. My app= is not working fast. It'= slow app=";

有必要更换符号" ="随着字母" s"通过以下条件:如果右边或左边有" ="标志有一封信,然后用字母" s"替换它。教授父词中的字母注册。如果你创建三种函数会更好。一个教授父母寄存器,第二个教授寄存器并替换大写字母" S"第三个是小写字母" s"。因此,将有三个结果:

我有很多网络APP S 。我的应用 s 无法正常运行。它' s 慢app s - 不区分大小写的正则表达式替换变体

我有很多网络APP S 。我的应用 S 无法正常工作。它' S 慢app S - 大写正则表达式替换变体

我有很多网络APP s 。我的应用 s 无法正常运行。它' s 慢app s 小写正则表达式替换变体

我的长码:

$search = array("a=", "b=", "c=", "d=", "e=", "f=", "g=", "h=", "i=","j=", "k=", "l=", "m=", "o=", "p=","r=", .... , "z=");
$replace s array("as", "bs", "cs", "ds", "es", "fs", "gs", "hs", "is","js", "ks", "ls", "ms", "os", "ps","rs", .... , "zs");
$result = str_ireplace($search, $replace, $text);

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

=(?=[\w'-])|(?<=[\w'-])=

并替换为:

“s”或“S”以获得您想要的结果。

但是,这将满足您输出的条件2和3。

对于条件1 ,您需要多个操作(如果您坚持只使用正则表达式解决方案):

操作1:

按此搜索:

=(?=[A-Z])|(?<=[A-Z])=

替换为:

"S"

操作2:

使用以下方法搜索操作1的结果:

=(?=[a-z0-9_'-])|(?<=[a-z0-9_'-])=

并替换为:

"s"

示例来源:(run here

<?php

$re11='/=(?=[A-Z])|(?<=[A-Z])=/';
$re12= '/=(?=[a-z0-9_\'-])|(?<=[a-z0-9_\'-])=/';
$re = '/=(?=[\w\'-])|(?<=[\w\'-])=/';
$str = 'I\'ve got a many web APP=. My app= is not working fast. It\'= slow app=';


echo "\n #### condition 1: all contexual upper or lowercase s \n";
$subst = 'S';
$result = preg_replace($re11,'S', $str);
$result = preg_replace($re12,'s', $result);
echo $result;




echo "\n ##### condition 2: all small case s \n";
$subst = 's';
$result = preg_replace($re, $subst, $str);
echo $result;

echo "\n ##### condition 3: all upper case S \n";
$subst = 'S';
$result = preg_replace($re, $subst, $str);
echo $result;

?>

示例输出:

 #### condition 1: all contexual upper or lowercase s 
I've got a many web APPS. My apps is not working fast. It's slow apps
 ##### condition 2: all small case s 
I've got a many web APPs. My apps is not working fast. It's slow apps
 ##### condition 3: all upper case S 
I've got a many web APPS. My appS is not working fast. It'S slow appS

Demo