我有一个来自for循环的字符串数据,我想从字符串中删除特定字符和特殊字符。请在我的数据下面查找。
["\r\n \r\n 300518<\/departureDate>\r\n\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t \r\n <\/availabilityDetails>\r\n
\r\n HYD<\/cityAirport>\r\n <\/departureLocationInfo>\r\n
\r\n DXB<\/cityAirport>\r\n <\/arrivalLocationInfo>\r\n
<\/availabilityProductInfo>702<\/orderClassesByCabin>
<\/cabinOption>",44,"AUHOT3116"]
我尝试了php中的str_replace和trim函数,但是没有用。我想从下面的字符串中取出来。
300518-departuredate-availabilityDetails-HYD-cityAirport-departureLocationInfo-DXB-
cityAirport-arrivalLocationInfo-availabilityProductInfo-702-
orderClassesByCabin-44-AUHOT3116
只需从该字符串中删除所有\,r,n,t。谁能帮我。我试图没有得到结果。谢谢前进。
答案 0 :(得分:1)
$cleanString = preg_replace('/\s+/', ' ', $yourString);
答案 1 :(得分:0)
请查看下面的代码:
<?php
//the data seems to be actually an array
$array = ["\r\n \r\n 300518<\/departureDate>\r\n\t\t\t\t\t\t\t\t\t \r\n\t\t\t\t\t\t\t\t\t \r\n <\/availabilityDetails>\r\n \r\n HYD<\/cityAirport>\r\n <\/departureLocationInfo>\r\n \r\n DXB<\/cityAirport>\r\n <\/arrivalLocationInfo>\r\n <\/availabilityProductInfo>702<\/orderClassesByCabin><\/cabinOption>",44,"AUHOT3116"];
//should yield
$desired_output = "300518-departuredate-availabilityDetails-HYD-cityAirport-departureLocationInfo-DXB-cityAirport-arrivalLocationInfo-availabilityProductInfo-702-orderClassesByCabin-44-AUHOT3116";
$trim = ["\t","\r","\n","<\/",">"," "]; //characters or substrings you want removed
foreach($array as &$value) {
$value = str_replace($trim,"-",$value); //removing unwanted characters
$value = preg_replace('/[- ]{2,}/','-',$value); //removing duplicates
$value = trim($value,"- "); //removing trailing and ending unwanted characters
}
$replaced_output = implode("-",$array); //converting the initial array to string
echo "<pre>";
var_dump($desired_output,$replaced_output);
请注意,期望的字符串和处理后的字符串并不相同,因为存在一个名为'cabinOption'的元素,该元素不符合删除条件,因此保持原样。
编辑:要使处理后的字符串与所需字符串相同,只需在$trim
数组中添加要删除的任何字符串即可。
这可能不是最好的方法,但这只是针对此特定情况的可能解决方案。您应该考虑使用更通用的方法,正则表达式等。