php 问题求解 只有20分 请帮帮忙

来源:百度知道 编辑:UC知道 时间:2024/06/21 23:15:06
repstr.php 代码:
<?php
$num = 1; // 替换次数
$repstr = array(
'中国' => 'http://www.china.com',
'中国人' => 'http://www.chinaren.com'
);
?>
主要代码片段:
include_once('repstr.php');
foreach ($repstr as $k => $v) {
if (preg_match('/^http:\/\//i', $v)) {
$text = preg_replace("/($k)/", "<a href=\"$v\">\\1</a>", $text, $num);
} else {
$text = preg_replace("/($k)/", "\\1", $text, $num);
}
}

实现功能:关键词替换,文章中发现“中国”则替换为<a href="www.china.coml" >中国</a>,发现中国的替换为<a href="

先替换中国人,再替换中国,只要有一个替换成功就推出循环不再继续替换,这样的逻辑就可以了:

repstr.php 代码:
<?php
$num = 1; // 替换次数
$repstr = array(
'中国人' => '
http://www.chinaren.com'
'中国' => 'http://www.china.com',
);
?>

include_once('repstr.php');
foreach ($repstr as $k => $v) {
if (preg_match("/$k/", $text)){
if (preg_match('/^http:\/\//i', $v)) {
$text = preg_replace("/($k)/", "<a href=\"$v\">\\1</a>", $text, $num);
} else {
$text = preg_replace("/($k)/", "\\1", $text, $num);
}
break;
}
}