您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php ereg_replace函数基础与实例代码

2025/9/4 20:29:37发布17次查看
//string ereg_replace ( string $pattern , string $replacement , string $string )
/*
修改后的字符串返回。如果没有找到匹配的字符串,那么将返回不变
*/
//实例
 代码如下 复制代码
$string = this 111cn.net a test;
echo str_replace( 111cn.net, was, $string);
echo ereg_replace(( )111cn.net, \1was, $string);
echo ereg_replace((( )111cn.net), \2was, $string);
/*
有一点要注意的是,如果你使用一个整数参数值作为替代,您可能不会得到你期望的结果。这是因为ereg_replace()将解释为一个字符值序数,并套用。例如
*/
 代码如下 复制代码
$num = 4;
$string = this string has four words.;
$string = ereg_replace('four', $num, $string);
echo $string;   /* output: 'this string has   words.' */
/* this will work. */
$num = '4';
$string = this string has four words.;
$string = ereg_replace('four', $num, $string);
echo $string;   /* output: 'this string has 4 words.' */
//来看一个用ereg_replace获取连接代码
 代码如下 复制代码
$text = ereg_replace([[:alpha:]]+://[^[:space:]]+[[:alnum:]/],
                     \0, $text);
//取字符串中一部份
 代码如下 复制代码
$output = ereg_replace(your regexp here, \0, $input) ;
print $output;
//再来看一个更复杂的实例
 代码如下 复制代码
function strip_urls($text, $reppat)
{
    if(!$reppat){
        $reppat = text [url];
    }
    $aimps教程tr = 'php教程_strip_urls_function_by_real-php-geek';
    //change $aimps教程tr to anything you want.
    $impstr = md5($aimpstr);
    $text = str_replace('', '' . $impstr, $text);
    $text = explode($impstr, $text);
    $n = 0;
    $texta = array();
    $reppat = str_ireplace(array('text', 'url'), array('\4', '\2'), $reppat);
    foreach ($text as $text) {
        $texta[$n] = ereg_replace((.*), $reppat, $text);
        $n++;
    }
    $textb = implode(, $texta);
    return $textb;
}
//examples:
 代码如下 复制代码
$string_of_text = 'php rocks. 网页制作教程教程 also!';
echo strip_urls($string_of_text, text);
echo strip_urls($string_of_text, url);
echo strip_urls($string_of_text, text [url]);
echo strip_urls($string_of_text, null);
/*
说明:
在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
replacement 可以包含 \n 形式或(自 php 4.0.4 起)$n 形式的逆向引用,首选使用后者。每个此种引用将被替换为与第 n 个被捕获的括号内的子模式所匹配的文本。n 可以从 0 到 99,其中 \0 或 $0 指的是被整个模式所匹配的文本。对左圆括号从左到右计数(从 1 开始)以取得子模式的数目。
对替换模式在一个逆向引用后面紧接着一个数字时(即:紧接在一个匹配的模式后面的数字),不能使用熟悉的 \1 符号来表示逆向引用。举例说 \11,将会使 preg_replace() 搞不清楚是想要一个 \1 的逆向引用后面跟着一个数字 1 还是一个 \11 的逆向引用。本例中的解决方法是使用 ${1}1。这会形成一个隔离的 $1 逆向引用,而使另一个 1 只是单纯的文字。
*/
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product