在给定字符串中的特定位置插入字符

时间:2015-05-20 18:09:10

标签: php regex

我正在努力学习正则表达式,这个问题对我来说似乎很难 我有这样的代码

$string = "He is type a document"

$ string是由用户在HTML表单textarea上输入的,现在我想将其更正为

$correct = "He is typing a document"

代码将扫描句子并停止后面的单词"他是" (或"她是","它是")然后添加" ing"到那个词的最后位置

2 个答案:

答案 0 :(得分:0)

^(?:s?he|it) is \S+\K

您可以ing使用此。替换。请参阅演示。

https://regex101.com/r/vA0yQ3/1

$re = "/^(?:s?he|it) is \\S+\\K/mi"; 
$str = "He is type a document\nshe is type a document\nit is type a document"; 
$subst = "ing"; 

$result = preg_replace($re, $subst, $str);

答案 1 :(得分:0)

您可以使用以下内容进行匹配:

(?<=(?:he is )|(?:she is )|(?:it is ))(\S*)\S

并替换为$1ing

请参阅DEMO

修改:要限制与ing匹配的字词,请使用以下内容:

(?<=(?:he is )|(?:she is )|(?:it is ))(\S*)\S(?<!ing)\b

修改:要使替换更有意义,请使用以下内容:

(?<=(?:he is )|(?:she is )|(?:it is ))(\S+?)[aeiou]?(?<!ing)\b

这将提供以下内容:

type -> typing
eat -> eating (not eaing)
break -> breaking (not breaing)
write -> writing

请参阅updated DEMO