0

I am trying to find the word and add a number next to it. How could he do? I tried with the code below, but I could not. Could anyone help me? Thank you!

$string = 'I220ABCD I220ABCDEF I220ABCDEFG'
if (preg_match("/I220.*/", $string, $matches)) {
    echo $matches[0];
}

Expected result: I220ABCD9 I220ABCDEF10 I220ABCDEFG11

4

5 回答 5

1

像这样使用preg_replace_callback

$str = 'I220AB FRRRR CD I221ABCDEF I220AB DSFDSF CDEFG';
$repl= preg_replace_callback('~(I220[^\s]+)~', function($m) {
         static $i=9;
         return $m[1] . $i++;
       }, $str);

echo $repl\n"; // I220AB9 FRRRR CD I221ABCDEF I220AB10 DSFDSF CDEFG
于 2013-04-18T22:14:41.813 回答
0

你需要在你的正则表达式中使用一个 catch 块"/I220([^ ]+)/",如果你想要它们,你也需要使用preg_match_all

于 2013-04-18T22:15:32.287 回答
0

我不知道您在最后添加数字的要求是什么,所以我只是在循环期间增加了;

$string = 'I220ABCD I220ABCDEF I220ABCDEFG';

$arrayStrings = explode(" ", $string);
$int = 9;
$newString = '';

foreach($arrayStrings as $stringItem)
{   
    if (preg_match("/I220.*/", $stringItem, $matches)) 
    {

        $stringItem = $stringItem.$int;
        $newString = $newString.$stringItem." ";
        $int++;
    }
}

echo $newString;
于 2013-04-18T22:20:48.407 回答
0

使用preg_replace_callback()

$string = 'I220ABCD I220ABCDEF I220ABCDEFG';
// This requires PHP5.3+ since it's using an anonymous function
$result = preg_replace_callback('/I220[^\s]*/', function($match){
    return($match[0].rand(0,10000)); // Add a random number between 0-10000
}, $string);

echo $result; // I220ABCD3863 I220ABCDEF5640 I220ABCDEFG989

在线演示

于 2013-04-18T22:25:08.177 回答
0

preg_replace_callback 满足您的需求:

    $string = 'I220ABCD I220ABCDEF I220ABCDEFG';


   class MyClass{

       private static $i = 9;

       private static function callback($matches){
           return $matches[0] . self::$i++;
       }

       public static function replaceString($string){
            return preg_replace_callback('/I220[^\s]+/',"self::callback",$string);  
       }
   }


   echo(MyClass::replaceString($string));

当然你可以编辑类来初始化你想要的方式

于 2013-04-18T22:31:46.377 回答