查找特定字符串的实例和下一个字符串的前两个字母,并交换它们在php中的位置


Finding the instance of a specific string and first 2 letters of next string and switch their places in php

我有一个特定的字符串,它是:

  <span style="color: green;">

我想要一个函数来查找这个字符串的实例,然后进一步查找下一个字符串的前两个字符是否为

我有逐字搜索的想法,但这将花费太长时间。有没有更短的解决办法?

输入:

  ab <span style="color: green;">  </strong>
输出:

  ab </strong> <span style="color: green;">  

强标签只是一个例子,它可以是/b,/i,/li或任何其他结束标签

您可以使用preg_replace,即:

$myHtml = <<< LOL
ab <span style="color: green;">  </strong>
LOL;   
$myHtml = preg_replace('%(<span style="color: green;">)(?:'s+)?(</.*?>)%i', '$2 $1', $myHtml);
echo $myHtml;
//ab </strong> <span style="color: green;">

span之后的任何标签都可以使用

演示:

http://sandbox.onlinephpfunctions.com/code/9dc934ece66856a92b041114140982dc822a6bec