2012-02-21 29 views
0

字符串从某一点替换字符串的一部分

abc/def/*

abc/def/*/xyz

如何使用preg_replace_callback具有一定的字符串/*后取代一切?

abc/def/replacement

+0

我不知道,但我猜你不想manualy再检查一下为“/ *”存在,那么该字符串切割成“位置/ * “然后添加替换? – kajacx 2012-02-21 20:02:32

+0

因此,在这两个示例中,结果都是相同的(您在“Like”下的值)? – salathe 2012-02-21 20:33:10

回答

1
<?php 
$string = "abc/dc/*bla/foo"; 

$string = preg_replace_callback(
    '~/\*.*~', 
    create_function(
     '$match', 
     'return "/replacement";' 
    ), 
    $string 
); 

var_dump($string); 
?> 

输出

string 'abc/dc/replacement' (length=19) 
1

像这样的东西应该工作:

$text = "abc/def/*/xyz"; 
function rep($matches) 
{ 
    return "/replacement"; 
} 
echo preg_replace_callback("|/\*.*|", "rep", $text); 

你真的需要使用preg_replace_ca尽管?下面是一个等价版本的preg_replace:

$text = "abc/def/*/xyz"; 
echo preg_replace("|/\*.*|", "/replacement", $text); 
相关问题