PHP | ereg_replace()函数

这个 ereg_replace() 是PHP中的内置函数,用于搜索其他字符串中的字符串模式。如果在原始字符串中找到模式,那么它将用替换字符串替换匹配的文本。你可以参考关于 正则表达式 了解使用正则表达式进行模式匹配的基本知识。

null

语法:

string ereg_replace ( $string_pattern, $replace_string,  $original_string )

使用的参数: 此函数接受三个必需参数,所有这些参数如下所述。

  • $string_模式 : 此参数指定要在$original_字符串中搜索的模式。它可以与数组和带括号的子字符串的字符串类型一起使用。
  • $replace_字符串 : 此参数指定将替换匹配文本的字符串,并可与数组和字符串类型一起使用。替换包含数字形式的子字符串,它将替换与数字匹配的文本的括号中的子字符串,并生成完整的内容字符串。
  • $original_字符串 : 此参数指定输入字符串,可以是数组类型,也可以是字符串类型。

返回值: 如果找到匹配项,此函数将返回修改后的字符串或数组。如果原始字符串中没有匹配项,那么它将返回未更改的原始字符串或数组。

注: 这个 ereg_replace() 功能是 区分大小写 在PHP中。这个功能是 反对 在PHP5.3.0中,以及 远离的 在PHP7.0.0中。

例如:

Input: $original_string = "Geeksforgeeks PHP article."; 
       $string_pattern = "(.*)PHP(.*)"; 
       $replace_string = " You should read \1all\2"; 
Output: You should read Geeksforgeeks all article.
Explanation: Within the parenthesis "1" and "2" to access
             the part of string and replace with 'PHP' to 'all'.

Input: $original_string = "Geeksforgeeks is no:one computer 
                                             science portal.";
       $replace_string = '1'; 
       $original_string = ereg_replace('one', $replace_string,
                                             $original_string);
Output: Geeksforgeeks is no:1 computer science portal. 

下面的程序说明了 ereg_replace() 作用

项目1:

<?php
// Original input string
$original_string = "Write any topic ." ;
// Pattern to be searched
$string_pattern = "(.*)any(.*)" ;
// Replace string
$replace_string = " own yours own \1biography\2" ;
echo ereg_replace ( $patternstrVal , $replacesstrVal , $stringVal );
?>


输出:

Write own yours own biography topic.

注: 当使用整数值作为替换参数时,由于函数将数字解释为字符的序数值,因此无法得到预期的结果。

项目2:

<?php
// Original input string
$original_string = "India To Become World's Fifth
Largest Economy In 2018.";
// Replace string
$replace_string = 5;
// This function call will not show the expected output as the
// function interpret the number to ordinal value of character.
echo ereg_replace ( 'Fifth' , $replace_string , $original_string );
$original_string = "India To Become World's Fifth
Largest Economy In 2018.";
// Replace String
$replace_string = '5' ;
// This function call will show
// the correct expected output
echo ereg_replace ( 'Fifth' , $replace_string , $original_string );
?>


输出:

India To Become World's  Largest Economy In 2018.
India To Become World's 5 Largest Economy In 2018.

参考 : http://php.net/manual/en/function.ereg-replace.php

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享