2013-02-12 48 views
5

我一直在试图让两个符号之间的文本被替换为preg_replace,但唉,仍然不完全正确,因为我得到一个空字符串的空输出,这就是我所拥有的远替换两个限制之间的文本

$start = '["'; 
$end = '"]'; 
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']); 

所以输出示例我正在寻找将是:

normal text [everythingheregone] after text 

normal text [test] after text 
+0

是文本始终不变后正常的文本和? – 2013-02-12 12:11:25

+1

'$ start'和'$ end'锚点必须是字符串,并且必须转义。你正在使用一个数组,而'['会是一个问题。 – mario 2013-02-12 12:11:36

+0

@Bhushan前后的文字都不会改变 – kabuto178 2013-02-12 12:13:21

回答

8

您正在将$ start和$ end定义为数组,但将其用作正常变量。试着改变你的代码如下:

$start = '\['; 
$end = '\]'; 
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']); 
+0

工作过,非常感谢:) – kabuto178 2013-02-12 12:35:44

0
$row['body']= "normal text [everythingheregone] after text "; 
$start = '\['; 
$end = '\]'; 
$msg = preg_replace('#'.$start.'.*?'.$end.'#s', '$1 [test] $3', $row['body']); 
//output: normal text [test] after text done 
1

如何

$str = "normal text [everythingheregone] after text"; 
$repl = "test"; 
$patt = "/\[([^\]]+)\]/"; 
$res = preg_replace($patt, "[". $repl ."]", $str); 

应该产生normal text [test] after text

编辑

小提琴演示here

+0

这给出了一个空白输出以及 – kabuto178 2013-02-12 12:31:11

+0

我刚更新了demo。这工作! – jurgemaister 2013-02-12 12:35:11

+0

正确,我失踪了;我的错误大声笑 – kabuto178 2013-02-12 12:36:50

0

我有一个正则表达式的方法。正则表达式是:\[.*?]

<?php 
$string = 'normal text [everythingheregone] after text '; 
$pattern = '\[.*?]'; 
$replacement = '[test]' 
echo preg_replace($pattern, $replacement, $string); 
//normal text [test] after text 
?> 
1

一些功能,可以帮助

function getBetweenStr($string, $start, $end) 
    { 
     $string = " ".$string; 
     $ini = strpos($string,$start); 
     if ($ini == 0) return ""; 
     $ini += strlen($start);  
     $len = strpos($string,$end,$ini) - $ini; 
     return substr($string,$ini,$len); 
    } 

function getAllBetweenStr($string, $start, $end) 
    { 
     preg_match_all('/' . preg_quote($start, '/') . '(.*?)' . preg_quote($end, '/') . '/', $string, $matches); 
     return $matches[1]; 
    } 
相关问题