PHP:替换字符

时间:2018-03-10 09:30:10

标签: php

我想替换字符串中的字符。我按照选定的角色搜索了位置,然后找到了'的位置,最终获得了0,5,16,20,47,56,65,70的位置。现在我想用$#44和5,47,65替换所有偶数位置(0,16,20,56,70)和$#55的奇数位置。

$find_char="'";
$left_replace_char = '$#44';
$right_replace_char = '$#55';
$string="'Like' this you 'get' your entire array in the 'variable' if the 'form'.";

$positions = array();
$pos = -1;
while (($pos = strpos($string, $find_char, $pos+1)) !== false) {
  $positions[] = $pos;
}
$result = implode(',',$positions);            
print_r($result); echo "<br/>";                    
foreach ($positions as $index=>$value) {
  if ($value % 2 == 0){
    $valEven[]=$value;                   
  } else {
    $valOdd []= $value;
  }    
}           
foreach ($valEven as $pos) {
  $strings = substr_replace($string, $left_replace_char, $pos, 1);
}           
foreach ($valOdd as $pos) {
  $strings = substr_replace($string, $right_replace_char, $pos, 1);
}
echo $strings;

它不起作用。请解决我的问题。

2 个答案:

答案 0 :(得分:1)

将您的问题解读为..

  

假设我有一个字符串'Like' this you 'get' your entire ...,我想要替换每个奇数   带有'的{​​{1}}的实例和带有$#44的每个偶数实例。

$#55

https://3v4l.org/EnJ9M

<强>结果:

<?php
$str = "'Like' this you 'get' your entire array in the 'variable' if the 'form'.";
$find = "'";

$result = null;
$odd = true;
for ($i=0; $i < strlen($str); $i++) {
    if ($str[$i] == $find) {
        $result .= $odd ? '$#44' : '$#55';
        $odd = !$odd;
    } else {
        $result .= $str[$i];
    }
}

echo $result;
?>

修改:OP希望替换多套。

$#44Like$#55 this you $#44get$#55 your entire array in the $#44variable$#55 if the $#44form$#55.

https://3v4l.org/EuSaV

<强>结果:

<?php
$str = "'Like' this you 'get' your entire array \"in\" the 'variable' if the 'form'.";

// for each item, have a matching $replace pair
$find = [
    '\'', 
    '"'
];

$replace = [
    ['$#44', '$#55'], // replaces ' 
    ['@', '@']        // replaces "
];

$result = null;
$odd = true;
for ($i=0; $i < strlen($str); $i++) {
    if (in_array($str[$i], $find)) {
        $key = array_search($str[$i], $find);
        $result .= $odd ? $replace[$key][0] : $replace[$key][1];
        $odd = !$odd;
    } else {
        $result .= $str[$i];
    }
}

echo $result;
?>

答案 1 :(得分:1)

这样可行:

$string = "'Like' this you 'get' your entire array in the 'variable' if the 'form'.";
$parts = explode("'",$string);
$isLeft = FALSE;
foreach ($parts as $key => $part) {
  if ($part != '') $parts[$key] = $isLeft ? '$#44'.$part : '$#55'.$part;
  $isLeft = !$isLeft;
}
echo implode('',$parts);

它并不漂亮,但它能完成这项工作。结果是:

  

$#44像$ 55这样你$#44 $ $ 55你的整个阵列   $#44变量$#55如果$#44形成$#55。

使用正则表达式的东西可能会短得多,也许会更好,但我总是难以理解它们。请参阅:https://regex101.com