如果&在index.php?a = 2之后存在

时间:2012-07-03 12:03:57

标签: php regex preg-replace

我需要替换链接index.php?a=2,但如果&之后有a=2,则不要替换它。 index.php?a=2 <- replace index.php?a=2&b=3 <- don't replace

使用PHPpreg_replace()

我尝试过使用它:

preg_replace('^index\.php\?a=([0-9]+)(?!amp;)^', 'home', 'index.php?a=2');
preg_replace('^index\.php\?a=([0-9]+)(?!amp;)^', 'home', 'index.php?a=2&b=3');
preg_replace('^index\.php\?a=([0-9]+)(?!&)^', 'home', 'index.php?a=2');
preg_replace('^index\.php\?a=([0-9]+)(?!&)^', 'home', 'index.php?a=2&b=3');

我正在使用:

preg_replace('^(\/*)index\.php\?a=([0-9]+)(?!&)^e', "a($2)", 'index.php?a=2');

function a($id) {
  // Getting name from mysql...
  return '/a$id_$name';
}

它正在使用此index.php?a=2&b0,但index.php?a=10&b=0没有。

3 个答案:

答案 0 :(得分:1)

PHP脚本:

<?php
print preg_replace('/index\.php\?a=[0-9]+(?!&)/', 'home', 'index.php?a=2');
print "\n";
print preg_replace('/index\.php\?a=[0-9]+(?!&)/', 'home', 'index.php?a=2&b=3'); 
?>

输出:

home
index.php?a=2&b=3

测试代码here

答案 1 :(得分:0)

'/index\.php\?a=[^&]+(?!&)/'

答案 2 :(得分:0)

'/index\.php\?a=\d+(?!\s*&)/'