3

php文字列$stringに重複した末尾のスラッシュが含まれているかどうかを検出したいと思います。

例えば:

$string = "http://somepage.com/something/some.html/////";

$string = "http://somepage.com/something/some.html";

そしてif、それが重複している場合は、次のようなことをしたい:

If ($string = "http://somepage.com/something/some.html/////";) {
    remove extra trailing slashes
} 
//else do nothing... 
4

5 に答える 5

9

rtrimこのように適用します

$string = rtrim($string, '/');
于 2012-12-21T12:33:40.433 に答える
6

あなたはただ使うことができますrtrim()

$string = rtrim($string, '/');

何らかの理由で最初に末尾のスラッシュがあるかどうかを確認したい場合は、次のように最後の文字を確認できます。

if ($string[ strlen($string)-1 ] === '/') {
    $string = rtrim($string, '/');
}

文字列を投げてrtrim()もコストがかからないので、最初に末尾のスラッシュをチェックする必要はありません。

正規表現を使用して末尾のスラッシュを削除するのは、少しやり過ぎです。

于 2012-12-21T12:40:06.157 に答える
3

複製できる場所があり/ます。たとえば、次のすべてのリンクから質問にアクセスできます。

/ここで違いを生むのはだけなhttp://ので、考えてみましょう。rtrim私が提供したほとんどの場合、単独では機能しないので、正規表現を使用しましょう。

解決

$parts = explode('//', $full_url, 2);
$parts[1] = rtrim(preg_replace('@/+@', '/', $parts[1]), '/');
$full_url = implode('//', $parts);
unset($parts);

ライブテスト: http://ideone.com/1qHR9o

Before: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes/
After:  https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes
---------------------
Before: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes////
After:  https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes
---------------------
Before: https://stackoverflow.com///questions///13990256///remove-duplicate-trailing-slashes////
After:  https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes
---------------------
Before: https://stackoverflow.com/questions//13990256/remove-duplicate-trailing-slashes//
After:  https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes
---------------------

説明

あなたの質問から、あなたは常に完全な URL を取得していることを理解しています。したがって、それを 2 つの部分に分割できます。

$parts = explode('//', $full_url, 2);

次に、重複/したものを次のように削除します。

preg_replace('@/+@', '/', $parts[1])

/次に、文字列の末尾から余分なものを削除します。

$parts[1] = rtrim( /*previous line*/ , '/');

そしてそれを内破します:

$full_url = implode('//', $parts);
unset($parts);
于 2012-12-21T12:47:56.530 に答える
3
$string = rtrim($string, '/');
于 2012-12-21T12:34:08.330 に答える
3

rtrimが最善の解決策ですがregex、完全を期すためにタグを付けたので:

$string = "http://somepage.com/something/some.html/////";
echo preg_replace('#/+$#','',$string);

>>> http://somepage.com/something/some.html

#   - Is the delimiter character 
/+  - Matches one or more forward slash
$   - Matches the end of the string
#   - Delimiter 
Replace with 
''  - Nothing (empty string)
于 2012-12-21T12:34:53.293 に答える