如何删除 php 中字符串的特定部分(冗余查询字符串)?

How to remove specific part(redundant querystring) of string in php?

如何从 url 中删除多个冗余查询字符串?

因此,就像下面的字符串,

Url:

localhost.com/en_ar/body?products_type=235&treatment=132?product_type=235&treatment=132&__from_store=en_bh

结果Url:

localhost.com/en_ar/body?product_type=235&treatment=132&__from_store=en_bh

如何使用 php.

?content? 之间的字符串中删除第一部分内容(如果存在于查询字符串中)

在我们的例子中,从字符串中删除内容 ?products_type=235&treatment=132?

您可以使用以下正则表达式 (DEMO):

(\?(?<=\?).*(?=\?))

它将四处寻找 ? 并匹配第 2 个 ? 之间的所有内容,以及第一个 ?.

以及以下PHP代码(DEMO):

$str = "localhost.com/en_ar/body?products_type=235&treatment=132?product_type=235&treatment=132&__from_store=en_bh";
$newStr = preg_replace('/(\?(?<=\?).*(?=\?))/', '', $str);
var_dump($newStr);

无论您的 url 中有 1 个、2 个还是更多 "sets of querystrings",我的 pattern/method 都会 match/consume 所有这些,但只捕获最后一个。因此,实际上只会执行 1 次替换,替换文本将是捕获的子字符串 (</code>).</p> <p>代码:(<a href="http://sandbox.onlinephpfunctions.com/code/d185f37c18a8fb5ad269435ac58cf75752f1847c" rel="nofollow noreferrer">Demo</a>)</p> <pre><code>$url='localhost.com/en_ar/body?abcd?products_type=235&treatment=1‌​32?product_type=235&‌​treatment=132&__from‌​_store=en_bh'; echo preg_replace('/(\?[^?]*)+/','',$url);

输出:

localhost.com/en_ar/body?product_type=235&‌​treatment=132&__from‌​_store=en_bh

图案说明:(只需14步Demo

/        // pattern delimiter
(        // start capture group
  \?     // match a question mark
  [^?]*  // greedily match zero or more non-question marks
)+       // end capture group -- repeat one or more times
/        // pattern delimiter