我有一个字符串$ IDN,如下所示:
C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G5
我正在使用preg_replace
将,
替换为新行,但我意识到,
包含在某些组织名称中,并且会删除组织名称。
我用这个:
$IDN = preg_replace('/, /u', "\r", $IDN);
我结束了这个:
C=US
O=VeriSign
Inc.
OU=VeriSign Trust Network
OU=(c) 2006 VeriSign
Inc. - For authorized use only
CN=VeriSign Class 3 Public Primary Certification Authority - G5
代码完成了它的设想,但正如你所看到的那样," VeriSign,Inc。"被砍掉,Inc
被移到一个新的行。
有什么建议可以避免这种情况吗?我想以某种方式过滤掉, Inc
,但不知道如何去做。
最终,我希望它最终看起来像这样:
C=US
O=VeriSign, Inc.
OU=VeriSign Trust Network
OU=(c) 2006 VeriSign, Inc. - For authorized use only
CN=VeriSign Class 3 Public Primary Certification Authority - G5
答案 0 :(得分:2)
使用分隔符列表' C =',' O =',' OU'和' CN'。之后,只需删除','从每一行的末尾开始。
http://php.net/manual/ru/function.strtr.php
<?php
$array_s = array('C=' => "\n", 'O=' => "\n", 'OU=' => "\n", 'CN=' => "\n"); // main separators
$string = "C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G5";
echo strtr(strtr($string, $array_s), array(", \n" => "\n"));
?>
如果要在输出字符串中保留分隔符,请使用此数组:
$array_s = array('C=' => "\nC=", 'O=' => "\nO=", 'OU=' => "\nOU=", 'CN=' => "\nCN=");
答案 1 :(得分:1)
您可以使用negative lookahead,即:
$string = "C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G5";
$result = preg_replace('/,\s+(?!Inc.)/', "\r", $string );
echo $result;