我有一个看起来像这样的字符串:
Bla bla%yada yada%bla bla%yada yada%
有没有办法只替换前两个“%”(或最后两个),这样我就可以得到下一个输出:
Bla bla <a href='link1'>yada yada</a> bla bla %yada yada%
并且如有必要,最后两个“%”也输出:
Bla bla <a href='link1'>yada yada</a> bla bla <a href='link2'>yada yada</a>
我无法弄清楚如何区分前两个和后两个,所以,如果我想,我可以用链接替换第一个或最后两个标记“%”。 我正在使用php。提前致谢
此致
答案 0 :(得分:3)
使用正则表达式(需要PHP 5.3+):
$string = 'Bla bla %yada yada% bla bla %yada yada%';
echo preg_replace('/%([^%]*)%/', '<a href="http://example.com">$1</a>', $string, 1) . '<br>'; // to replace the first instance.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
$links = array('http://example.com', 'http://stackoverflow.com', 'http://google.com');
$index = 0;
echo preg_replace_callback('/%([^%]*)%/', function($m) use($links, &$index){
$m[1] = '<a href="'.$links[$index].'">'.$m[1].'</a>';
$index++;
// reset the index if it exceeds (N links - 1)
if($index >= count($links)){
$index = 0;
}
return $m[1];
}, $string).'<br>'; // to replace according to your array
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// To test with a string that contains more %% than the links
$string2 = 'Bla bla %yada yada% bla bla %yada yada% wuuut dsfsf %yada yada% sjnfsf %yada yada% jnsfds';
$links = array('http://example.com', 'http://stackoverflow.com', 'http://google.com');
$index = 0;
echo preg_replace_callback('/%([^%]*)%/', function($m) use($links, &$index){
$m[1] = '<a href="'.$links[$index].'">'.$m[1].'</a>';
$index++;
// reset the index if it exceeds (N links - 1)
if($index >= count($links)){
$index = 0;
}
return $m[1];
}, $string2).'<br>'; // to replace according to your array
答案 1 :(得分:0)
试试这个
支持PHP 4和PHP 5
<强>解决方案:强>
$string ='Bla bla %yada yada% bla bla %yada yada%';
// Count no of %
$count = substr_count($string,'%');
// Valid string pattern
if ( 0 == ($count % 2) ) {
$urlString = $string;
// Iterate for each pair of % to make it link
for ( $i=1; $i <= $count/2 ; $i++ ) {
$urlString = preg_replace('/%/', "<a href='link$i'>", $urlString, 1);
$urlString = preg_replace('/%/', "</a>", $urlString, 1);
}
}
// Invalid string pattern
else {
echo "Invalid string pattern";
}
// Display generated link
echo $urlString;
使用preg_replace函数
$str ='Bla bla %yada yada% bla bla %yada yada%';
$newStr = preg_replace('/%/', '', $str, 2);
echo $newStr;
// Output => Bla bla yada yada bla bla %yada yada%
$str ='Bla bla %yada yada% bla bla %yada yada%';
$newStr = preg_replace('/%/', '', strrev($str), 2);
$newStr = strrev($newStr);
echo $newStr;
// Output => Bla bla %yada yada% bla bla yada yada
$str ='Bla bla %yada yada% bla bla %yada yada%';
$newStr = preg_replace('/%/', '', $str);
echo $newStr;
// Output => Bla bla yada yada bla bla yada yada