Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php str_是否替换任何号码?_Php_Numbers_Str Replace - Fatal编程技术网

Php str_是否替换任何号码?

Php str_是否替换任何号码?,php,numbers,str-replace,Php,Numbers,Str Replace,我有一个关于str_替换任何号码的小问题 $jud='Briney Spears 12 2009'; $jud=str_replace(array('2007','2008','2009','2010','2011','2012'),'2013',$jud); $jud=str_replace(array('0'),'',$jud); $jud=str_replace(array('1'),'By',$jud); $jud=str_replace(array('2'),'Gun',$

我有一个关于str_替换任何号码的小问题

$jud='Briney Spears 12 2009';

$jud=str_replace(array('2007','2008','2009','2010','2011','2012'),'2013',$jud);

$jud=str_replace(array('0'),'',$jud);  
$jud=str_replace(array('1'),'By',$jud);  
$jud=str_replace(array('2'),'Gun',$jud);  
$jud=str_replace(array('3'),'Fast',$jud);

echo $jud ;
结果是

用枪射击的布氏长矛

有人能帮忙吗?我正在寻找“2013年比根盐碱矛”的结果如何?
谢谢

我不知道我是否正确理解了你的问题。但你可以做到:

$jud='Briney Spears 12 2009';
$jud=str_replace(" 12 ", " ByGun ", $jud);
例如,这将以ByGun取代12,而不会取代2012。如果需要所有月份,可以将“1”到“12”放在一个数组中。保持前后的空间

$jud=str_replace(array(" 1 "," 2 "," 3 "," 4 "," 5 "," 6 "," 7 "," 8 "," 9 "," 10 "," 11 "," 12 "), " ByGun ", $jud);

然后,替换年份,就像您所做的那样。

尝试用一些占位符替换年份。例如:

$jud = str_replace(array('2007','2008','2009','2010','2011','2012'), '%%YEAR%%', $jud);
然后替换数字

$jud=str_replace(array('0'),'',$jud);
$jud=str_replace(array('1'),'By',$jud);
$jud=str_replace(array('2'),'Gun',$jud);
$jud=str_replace(array('3'),'Fast',$jud);
然后将占位符替换为年份:

$jud = str_replace('%%YEAR%%', 2013, $jud);

您可以更改替换顺序(一年后替换)或使用数组方法替换
str_replace()

只是为了好玩:)


问题在于操作顺序。如果先用2013年替换所有年份,然后分别替换出现的
0
1
2
3
2013
将被替换。
$sentence    = 'Britney Spears 12 2009';
$toreplace   = array('2009', '2012');
$replacewith = array('2013', '2013');

echo str_replace($toreplace, $replacewith, $sentence); // Britney Spears 12 2013
<?php
  $jud = 'Briney Spears 12 2009';
  $rep = array('', 'By', 'Gun', 'Fast');

  echo preg_replace(
    array_merge( array('/20(0[\d]|1[1-2])/'), 
      array_map( function($foo){
        return "/{$foo}(?![\d]{2,})(?!$)/";
      }, array_keys($rep))), 
        array_merge( array('2013'), $rep ), $jud, 1);