在php中排序后从数组中删除字符

时间:2017-08-30 13:33:31

标签: php strtr

我在PHP中按字母顺序从一个完美的文本文件中排序数据,但不幸的是,自动填充的文本文件包含#039等字符。我希望从endresult中删除。尝试了很多东西来替换和删除字符,但没有成功。这就是我到目前为止所做的:

    <?php
error_reporting(E_ALL);

$fileName = 'cache/_city.txt';
$data     = file_get_contents($fileName);

// Assuming that the file had the data in one line...

// Split the data using the delimiter
$split = explode("|", $data);

// Sort
sort($split);

// Put it all back together
$data = implode("&nbsp", $split);
$data = str_replace("&#039;" , "", $data);

echo $data;

?> 

如何从$ data中删除这段文字:#039;

示例数据:

<a href="?city=Leiden">Leiden</a>|
<a href="?city=Papendrecht">Papendrecht</a>|
<a href="?city=Helmond">Helmond</a>|
<a href="?city=%26%23039%3Bs-Hertogenbosch">&amp;#039;s-Hertogenbosch</a>|
<a href="?city=Hengelo">Hengelo</a>|
<a href="?city=Marknesse">Marknesse</a>|
<a href="?city=Wanssum">Wanssum</a>|
<a href="?city=Rijswijk">Rijswijk</a>|
<a href="?city=Leunen">Leunen</a>|
<a href="?city=Genemuiden">Genemuiden</a>|

2 个答案:

答案 0 :(得分:1)

问题中没有足够的信息来说明您要替换的内容。这基本上决定了答案。

如果您只想更换几个特定字符,最好使用str_replace或其变体,但如果它是一些“垃圾”字符(在您的答案中暗示),则可以替换例如,Unicode范围(带preg_replace)。有人在这里问了一个简单的答案:How do I replace characters not in range [0x5E10, 0x7F35] with '*' in PHP?

功能参考:

https://secure.php.net/manual/en/function.str-replace.php https://secure.php.net/manual/en/function.preg-replace.php

附注:您应该使用&nbsp;,而不是&nbsp

修改:根据您提供的新信息,您似乎正在尝试删除已编码的字符,请尝试:str_replace('&#039;', '', urldecode($data))

答案 1 :(得分:0)

你有没有尝试过这样的事情:

$data = str_replace($wrongChar , "", $data);

编辑:

即使我认为你会比你需要的更“干净”,你能测试一下吗?

$data = file_get_contents($fileName);
$data = preg_replace('/[^A-Za-z0-9\-]/', '', $data);

第二版:

知道* _replace正在运行,我的建议有所改善。

<?php

error_reporting(E_ALL);

// It will apply html_entity_decode serveral times on the string to convert all HTML entities
$recursive_decode = function($str, $depth = 1) use (&$recursive_decode) {
    if (!$depth) {
        return $str;
    }

    return $recursive_decode(html_entity_decode($str, ENT_QUOTES, 'UTF-8'), --$depth);
};

$fileName = 'cache/_city.txt';

// In this test, try with a depth egals to 2
$data     = $recursive_decode(file_get_contents($fileName), 2);

// Assuming that the file had the data in one line...

// Split the data using the delimiter
$split = explode('|', $data);

// Sort
sort($split);

// Put it all back together
$data = implode("&nbsp", $split);

// Because recursive_decode converted all entities, your previous "&#039" is now "'"
$data = str_replace("'" , "", $data);

echo $data;

?>