我正在尝试将 转换为whitespace。
然后使用preg_replace执行一些Regex操作。
就像这样。
$title = " TEST Ok.2-2";
$title = mb_convert_encoding($title, 'UTF-8', 'HTML-ENTITIES');
//$title = html_entity_decode($title, ENT_NOQUOTES, 'UTF-8');
//( MEAN: I can use mb_convert_encoding() or html_entity_decode())
//GOT the same out put = TEST < Ok.2-2.
//So now I have TEST < Ok.2-2
//I want to make a space on Ok so I use preg_replace()
$replace = "~\s+(ok[.]?)~i";
$title = preg_replace($replace, ' OK. ', $title, -1);
$title = preg_replace('/\s+/', ' ', $title);
$title = trim($title);
//The result = TEST < Ok.2-2 (not work!)
echo($title);使用这段代码,mb_convert_encoding和html_entity_decode工作得很好,但是当我尝试使用preg_replace来调整空白时,似乎找不到转换过的空格。
现在输出:TEST < Ok.2-2
预期产出:TEST < OK. 2-2
现在是我的解决方案
我将str_replace添加到硬代码中,将 替换为空白,并使用mb_convert_encoding或html_entity_decode来转换另一个added实体。
$title = ' TEST < Ok.2-2';
$title = str_replace(' ', ' ', $title);
$title = mb_convert_encoding($title, 'UTF-8', 'HTML-ENTITIES');
//$title = html_entity_decode($title, ENT_NOQUOTES, 'UTF-8');
//( MEAN: I can use mb_convert_encoding() or html_entity_decode())
//GOT the same out put = TEST < Ok.2-2.
//So now I have TEST < Ok.2-2
//I want to make a space on Ok so I use preg_replace()
$replace = '~\s+(ok[.]?)~i';
$title = preg_replace($replace, ' OK. ', $title, -1);
$title = preg_replace('/\s+/', ' ', $title);
$title = trim($title);
//The result TEST < OK. 2-2 (WORK!)
echo($title);现在我的输出:TEST < OK. 2-2
我的期望:TEST < OK. 2-2
有最好的解决方案吗?
发布于 2015-06-12 15:15:55
我想这会给你你想要的。
$title = trim(
preg_replace('~\s+~', ' ',
str_ireplace(array(' ', ' ok.'), array(' ', ' OK. '),
" TEST Ok.2-2")
)
);这将:
trim)preg_replace('~\s+~', ' ')替换多个空白 替换为单个空间(str_ireplace)ok.大小写不敏感于OK. (str_ireplace)输出:
测试好了。2-2
您的HTML实体解码示例是正确的,http://sandbox.onlinephpfunctions.com/code/eed7e30d507f7197585f29c1fdde9e7744fc572d
$title = html_entity_decode(" TEST Ok.2-2", ENT_NOQUOTES, 'UTF-8');
echo $title;输出:
测试测试Ok.2.2-2
编辑:
<?php
$title = ' TEST < Ok.2-2';
$title = trim(preg_replace('~\s+~', ' ', str_ireplace(array(' ', '<', 'Ok.'), array(' ', '', ' OK. '), $title)));
echo $title;使用str_replace删除这两个实体可能更安全。如果您的字符串是<h1> TEST < Ok.2-2</h1>,并且已经解码,那么删除所有的<,您的字符串就不会像原来那样起作用了。
输出:
测试好了。2-2
https://stackoverflow.com/questions/30805980
复制相似问题