1

我在 PHP 中从一个完美的文本文件中按字母顺序对数据进行排序,但不幸的是,自动填充的文本文件包含 #039 之类的字符;我想从最终结果中删除。尝试了很多方法来替换和删除字符,但没有成功。这是我到目前为止所拥有的:

    <?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>|
4

2 回答 2

1

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

如果您只想替换几个特定字符,最好使用它str_replace或其变体,但如果它是多个“垃圾”字符(在您的答案中暗示),您可以替换 Unicode 范围(用preg_replace),例如例子。有人问并在这里得到了一个简单的答案:如何在 PHP 中用 '*' 替换不在 [0x5E10, 0x7F35] 范围内的字符?

功能参考:

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))

于 2017-08-30T13:42:08.140 回答
1

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

$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;

?>
于 2017-08-30T13:43:24.347 回答