Php 如何替换默认位置的字符串?
我有以下代码:Php 如何替换默认位置的字符串?,php,Php,我有以下代码: $text = "abc def abc jkl mno"; $regex = '/'.trim('abc').'/ism'; $search = array(); if(preg_match_all($regex, $text, $tmp)) { if(isset($tmp[0])) { for($i = 0;$i < count($tmp[0]); $i++) {
$text = "abc def abc jkl mno";
$regex = '/'.trim('abc').'/ism';
$search = array();
if(preg_match_all($regex, $text, $tmp)) {
if(isset($tmp[0])) {
for($i = 0;$i < count($tmp[0]); $i++) {
$search = $tmp[0][1];
$replace = 'ghi';
$article = str_replace($search, $replace, $text);
}
}
}
echo $article;
$text=“abc def abc jkl mno”;
$regex='/'.trim('abc')。/ism';
$search=array();
if(preg_match_all($regex,$text,$tmp)){
if(isset($tmp[0]){
对于($i=0;$i
当我echo$article_text
时,结果是:ghi def ghi jkl mno
但是我想要的结果是abc def ghi jkl mno。如何修复此问题?尝试以下方法:
试试这个:
您可能希望PREG_OFFSET_CAPTURE选项用于PREG_match_all,因此您可以同时获得匹配字符串及其字符串偏移量:您可能希望PREG_OFFSET_CAPTURE选项用于PREG_match_all,因此您可以获得匹配字符串及其字符串偏移量:
$text = "abc def abc jkl mno";
$search = 'abc';
$replace = 'ghi';
$article = substr($text, 0, strlen($search)) . str_replace($search, $replace, substr($text, strpos($text, 'abc') + strlen($search)));
echo $article;