PHP:匹配字符串,同时忽略引号内的转义引号
匹配包含在单引号 (') 和双引号 (") 内的字符串,您可以使用以下常规表达式:
<br>$code = preg_replace_callback( '/"(.*?)"/', array( &$this, '_getPHPString' ), $code );<p>$code = preg_replace_callback( "#'(.*?)'#", array( &$this, '_getPHPString' ), $code );<br>
但是,这些表达式不考虑字符串中的转义引号。要忽略转义引号,您可以使用更复杂的正则表达式:
好(但是效率低下):
<br>"(<sup><a href="https://www.php.cn/link/d58f36f7679f85784d8b010ff248f898" rel="nofollow" target="_blank">1</a></sup>|.)*"<br>
更好(通过特殊功能更高效量词):
<br>"(<sup><a href="https://www.php.cn/link/960fe54b16d890a75e845fcd23afc32d" rel="nofollow" target="_blank">2</a></sup> |.)*"<br>
最佳(展开时最有效循环):
<br><sup><a href="https://www.php.cn/link/84fec9a8e45846340fdf5c7c9f7ed66c" rel="nofollow" target="_blank">3</a></sup><em>(?: .<sup><a href="https://www.php.cn/link/9b1cab1b93285ce58e7c1dc576ff8a14" rel="nofollow" target="_blank">4</a></sup></em>)*<br>
这些改进的表达式将允许在各自的带引号字符串中忽略转义引号(' 和 ")。对于 PHP 语法,请使用以下内容:
<br>$re_dq = '/"<sup><a href="https://www.php.cn/link/b594f8f8fcc3cc7910e2dcd4269a2e95" rel="nofollow" target="_blank">5</a></sup><em>(?:\.<sup><a href="https://www.php.cn/link/096ce33c96792e289516407eb29b62bb" rel="nofollow" target="_blank">6</a></sup></em>)*"/s';<br> $re_sq = "/'<sup><a href="https://www.php.cn/link/57947ed4d4130c7ff0a057c8654dd1a3" rel="nofollow" target="_blank">7</a></sup><em>(?:\.<sup><a href="https://www.php.cn/link/7835a9ef21ac8378a23835829594d598" rel="nofollow" target="_blank">8</a></sup></em>)*'/s";<br>
这些正则表达式可以提供准确、高效的字符串匹配,即使在处理转义引号。
以上是如何在 PHP 中有效匹配带引号的字符串,忽略转义引号?的详细内容。更多信息请关注PHP中文网其他相关文章!