Home > Backend Development > PHP Tutorial > PHP 正则匹配 求解答

PHP 正则匹配 求解答

WBOY
Release: 2016-06-06 20:29:49
Original
1062 people have browsed it

<code><?php $str = "0123ABCDFWS\",.?<>{}[]*&^%#@!~()+-|:;";
$str = iconv('utf-8', 'gbk//ignore', $str);
$str = preg_replace('/\xa3([\xa1-\xfe])/e', 'chr(ord(\1)-0x80)', $str);
echo $str;
?></code>
Copy after login
Copy after login

这是网上找的一段全角符号转半角符号的函数,使用了下确实有效,使用的原理是中文标点的第二个字节减去0X80(即128)所得的数字就是半角所得的数字,但还是不符合我的需求,我希望的能够从一段文本中将全角符号转成半角符号而对文字不转换。

例如:

原文:如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义。
转为:如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义.

请问这个该如何匹配???

还是需要说将文本中的字符串转成数组,例遍数组遇到全角转成半角,再组成文本。

<code><?php // 半角返回0,全角返回1
function DBCorSBC($char) {
    $ascii = ord($char);
    if ($ascii < 128) {
        return 0;
    }   
    else {
        return 1;
    }   
}</code></code>
Copy after login
Copy after login

回复内容:

<code><?php $str = "0123ABCDFWS\",.?<>{}[]*&^%#@!~()+-|:;";
$str = iconv('utf-8', 'gbk//ignore', $str);
$str = preg_replace('/\xa3([\xa1-\xfe])/e', 'chr(ord(\1)-0x80)', $str);
echo $str;
?></code>
Copy after login
Copy after login

这是网上找的一段全角符号转半角符号的函数,使用了下确实有效,使用的原理是中文标点的第二个字节减去0X80(即128)所得的数字就是半角所得的数字,但还是不符合我的需求,我希望的能够从一段文本中将全角符号转成半角符号而对文字不转换。

例如:

原文:如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义。
转为:如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义.

请问这个该如何匹配???

还是需要说将文本中的字符串转成数组,例遍数组遇到全角转成半角,再组成文本。

<code><?php // 半角返回0,全角返回1
function DBCorSBC($char) {
    $ascii = ord($char);
    if ($ascii < 128) {
        return 0;
    }   
    else {
        return 1;
    }   
}</code></code>
Copy after login
Copy after login

你的方法不错,不过复杂了点,看我的

<code>$arr1 = ["1","2","3","A","B","C","D","F","W","S","\",""",",",".","?","<",">","{","}","[","]","*","&","^","%","#","@","!","~","(",")","+","-","|",":",";","。"];
$arr2=["1","2","3","A","B","C","D","F","W","S","\\","\"",",",".","?","","{","}","[","]","*","&","^","%","#","@","!","~","(",")","+","-","|",":",";","."];
$str="如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义。";
echo $str."<br>";
for ($i=0;$i<count echo></count></code>
Copy after login

运行结果

<code>如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义。
如果我连身边最重要的人都保护不了的话,我当这个魔君还有什么意义.</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template