猿问

如何使用 substr 和 strrpos 来清理特定字符后的字符串?

我想从以下字符串中删除我设置的关键字之后的任何内容。请记住, url 变量只是一个示例,在现实生活中它可以采用多种形式。


例如,以下,


$url = '/resutls?offer=1&gclid=CjwKCAjw1f_pBRAEEiwApp0JK';

我希望它是


/resutls?offer=1


但是当我使用以下代码时


$url = substr($url, 0, strrpos( $url, '&gclid'));

$url = substr($url, 0, strrpos( $url, '&utm_source'));

$url = substr($url, 0, strrpos( $url, '?utm_campaign'));

$url = substr($url, 0, strrpos( $url, '?utm_medium'));

$url = substr($url, 0, strrpos( $url, '?token'));

$url = substr($url, 0, strrpos( $url, '&fbclid'));

$url = substr($url, 0, strrpos( $url, '&utm_campaign'));

$url = substr($url, 0, strrpos( $url, '&utm_medium'));

$url = substr($url, 0, strrpos( $url, '&token'));


echo $url;

url 变量返回空。


我怎样才能解决这个问题?


呼啦一阵风
浏览 183回答 3
3回答

慕少森

尝试这个<?php$url = '/resutls?offer=1&gclid=1&utm_source=21213';$url = strrpos( $url, '&gclid')?substr($url, 0, strrpos( $url, '&gclid')):$url;&nbsp;$url = strrpos( $url, '&utm_source')?substr($url, 0, strrpos( $url, '&utm_source')):$url;&nbsp;$url = strrpos( $url, '?utm_campaign')?substr($url, 0, strrpos( $url, '?utm_campaign')):$url;$url = strrpos( $url, '?utm_medium')?substr($url, 0, strrpos( $url, '?utm_medium')):$url;$url = strrpos( $url, '?token')?substr($url, 0, strrpos( $url, '?token')):$url;$url = strrpos( $url, '&fbclid')?substr($url, 0, strrpos( $url, '&fbclid')):$url;$url = strrpos( $url, '&utm_campaign')?substr($url, 0, strrpos( $url, '&utm_campaign')):$url;$url = strrpos( $url, '&utm_medium')?substr($url, 0, strrpos( $url, '&utm_medium')):$url;$url = strrpos( $url, '&token')?substr($url, 0, strrpos( $url, '&token')):$url;echo $url;?>

隔江千里

使用parse_url()和parse_str()获取您想要的任何关键字。$parsed = parse_url('/resutls?offer=1&gclid=CjwKCAjw1f_pBRAEEiwApp0JK');parse_str($parsed['query'], $output);echo($output['offer']);&nbsp; // should print 1您也可以使用它来重建您的 URL:echo $parsed['path'] . '?offer=' . $output['offer']; // prints /resutls?offer=1

30秒到达战场

我已经将“如果找到后删除”包装到一个函数中。这首先检查字符串是否存在,然后如果存在,它将执行该substr()部分...function trimIfSet ( string $base, string $pattern )&nbsp; &nbsp;{&nbsp; &nbsp; if (( $pos = strrpos($base, $pattern)) !== false ){&nbsp; &nbsp; &nbsp; &nbsp; $base = substr($base, 0, $pos);&nbsp; &nbsp; }&nbsp; &nbsp; return $base;}$url = '/resutls?offer=1&gclid=CjwKCAjw1f_pBRAEEiwApp0JK';$url = trimIfSet( $url, '&gclid');$url = trimIfSet( $url, '&utm_source');echo $url;
随时随地看视频慕课网APP
我要回答