简体   繁体   English

PHP Escaping 数组内字符串中的特殊字符

[英]PHP Escaping special characters in a string inside an array

I'm trying to load all my preg_replace requirements into an array.我正在尝试将我所有的 preg_replace 要求加载到一个数组中。 They're a bit complicated, since they're all regular expressions and XML tags.它们有点复杂,因为它们都是正则表达式和 XML 标签。

This is the way the plain preg_replace is:这是普通 preg_replace 的方式:

$content = preg_replace('/\<MESSAGE(.*?)>/im','<MESSAGE>',$content);

I'm trying to do:我正在尝试做:

$stripData = array( '/\<MESSAGE(.*?)>/im','<MESSAGE>', )

But when I do print_r($stripData), I get Array ( [/\/im] => )但是当我执行 print_r($stripData) 时,我得到Array ( [/\/im] => )

What's happening here?这里发生了什么事? Certain parts are not included in the array string at all.某些部分根本不包含在数组字符串中。

I was expecting to get print_r as Array ( [/\<MESSAGE(.*?)>/im] => <MESSAGE>)我期待将 print_r 作为Array ( [/\<MESSAGE(.*?)>/im] => <MESSAGE>)

The problem you're reporting is related with the browser parsing the <MESSAGE(.*?)> as an HTML tag.您报告的问题与将<MESSAGE(.*?)>解析为 HTML 标记的浏览器有关。 My comment is correct about specifying the problem, but the using of <pre> tag is wrong as it won't solve the problem.我对指定问题的评论是正确的,但是使用<pre>标签是错误的,因为它不能解决问题。 The solution is encoding the array string using htmlentities method like this:解决方案是使用htmlentities方法对数组字符串进行编码,如下所示:

echo htmlentities(print_r($stripData, 1));

This will produce the following result:这将产生以下结果:

Array
(
    [0] =&gt; /\&lt;MESSAGE(.*?)&gt;/im
    [1] =&gt; &lt;MESSAGE&gt;
)

Which will be visible on the browser like this:这将在浏览器上可见,如下所示:

Array ( [0] => /\<MESSAGE(.*?)>/im [1] => <MESSAGE> )

Simply by using htmlentities function:只需使用 htmlentities function:

htmlentities(print_r($stripData, true));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM