在PHP中的第四个斜杠后删除字符串的一部分

时间:2019-02-15 05:28:33

标签: php

我有一个包含链接的数组,并尝试编辑这些链接。尝试在第四个斜杠后剪切链接。

  [0]=>
  string(97) "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline"
  [1]=>
  string(105) "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline"
  [2]=>
  string(91) "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline"

预期的输出是这样的:

  [0]=>
  string(97) "https://www.nowhere.com./downtoalley/"
  [1]=>
  string(105) "https://www.example.com./wowar-waseda/"
  [2]=>
  string(91) "https://www.hey.com./gotoashbourn/"

长度不同,所以我不能为此使用strtok其他任何选项吗?

3 个答案:

答案 0 :(得分:3)

尝试以下代码:

<?php
$arr = array(
0 => "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
1 => "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
2 => "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");

$resultArray = array();
foreach($arr as $str) {
    array_push($resultArray, current(explode("?",$str)));   
}
print_r($resultArray);

?>

您可以测试此代码here

答案 1 :(得分:2)

使用此正则表达式,您可以使用preg_replace将第四个/之后的每个字符串中的所有内容替换为空白

^(([^/]*/){4}).*$

查找四组非/字符,后跟/,将这些文本收集到捕获组1中;然后用$1代替,它仅给出第4个/的文本:

$strings = array("https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
"https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
"https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");
print_r(array_map(function ($v) { return preg_replace('#^(([^/]*/){4}).*$#', '$1', $v); }, $strings));

输出:

Array (
    [0] => https://www.nowhere.com./downtoalley/
    [1] => https://www.example.com./wowar-waseda/
    [2] => https://www.hey.com./gotoashbourn/ 
)

Demo on 3v4l.org

答案 2 :(得分:0)

没有直接功能可实现此目的。您可以按照下面的PHP代码进行操作:

$explodingLimit = 4;
$string = "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline";
$stringArray = explode ("/", $string);
$neededElements = array_slice($stringArray, 0, $explodingLimit);
echo implode("/", $neededElements);

我为一个可以用于数组的元素做了这个。如果需要,您还可以添加最后一个'/'。希望对您有帮助。