簡體   English   中英

php 中的字符串 function (str_replace)

[英]String function (str_replace) in php

我有一個 PHP function 如下:

<?php
function fixEncoding ($str){
    $searchVal = array("?", "=", ":", ";", "#", "+", "%", "&" );
    $replaceVal = array("%3F", "%3D", "%3A", "%3B", "%23", "%2B", "%25", "%26" );
    return str_replace($searchVal, $replaceVal, $str);  
}
$test_string = "www.joensuu.fi/documents/144181/2569169/Joensuun-Areena.jpg/69933c17-e619-7d05-a64a-94bfbb533da9?t=1550323540726";
$result = fixEncoding($test_string);
echo $result;
?>

Output:

www.joensuu.fi/documents/144181/2569169/Joensuun-Areena.jpg/69933c17-e619-7d05-a64a-94bfbb533da9%253Ft%253D1550323540726

這個 function 成功替換 '?' 和 '=' 字符,但是,它后來也用 '%25' 替換了它們的 '%' 字符,這並不意味着它是預期的 output。 任何建議,關於我如何處理這個問題。

把 % 首先放在你的數組中,比如

$searchVal = array("%", "?", "=", ":", ";", "#", "+", "&" );

但您也應該考慮使用 JureW 的答案

如果我對你的理解正確,你想要這樣的東西:

www.joensuu.fi%2Fdocuments%2F144181%2F2569169%2FJoensuun-Areena.jpg%2F69933c17-e619-7d05-a64a-94bfbb533da9%3Ft%3D1550323540726

如果是這樣,則無需構建自己的 function:

print_r(urlencode($test_string)); // outputs same as example above

PHP 內置了 function 用於編碼/解碼 url,所以我們不要重新發明輪子並使用它們:)

嘗試這個:

function fixEncoding ($str){
    return urlencode($str);
}

$test_string = "test???";
$result = fixEncoding($test_string);
echo $result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM