在php中将一个字符串替换为多个字符串


replace one char string into many chars string in php

如何将字符串中的一个单词替换为两个单词。我的意思是,我试图将"x"替换为其他

 <?php
    $equation = 'sin(x)';
    $length = strlen($equation);
    for($i=0; $i<$length; $i++) {
        if($equation[$i] == 'x') {
            $equation[$i] = substr_replace('x','90',$equation);
            echo $equation.'<br>';
            calc($equation);
        }
    }
?>

然而,它只读取第一个值9。但当我只输入一个数字时,例如

 <?php
    $equation = 'log(x)';
    $length = strlen($equation);
    for($i=0; $i<$length; $i++) {
        if($equation[$i] == 'x') {
            $equation[$i] = substr_replace('x','1',$equation);
            echo $equation.'<br>';
            calc($equation);
        }
    }
?>

它可以使用一些其他代码来接收和评估方程。那么,有办法吗?

您不应该手动循环字符串!函数就是这样做的!

使用str_replace:

<?php
$equation = 'log(x)';
str_replace("x","90", $equation);
echo $equation.'<br>';
calc($equation);
?>

大家好,欢迎来到stackoverflow。你不需要循环你的字符串。现有函数替换字符串的一部分。

str_replace(搜索、替换、主题)

preg_replace(模式、替换、受试者)

等等。

在你的情况下,你可以这样做:

$equation = 'sin(x)';
$equation = str_replace('(x)', '('.$yourValue.')', $equation);

编辑/注意:我不只是替换"x",而是替换"(x)",如果你的字符串中有多个x,并且你只想替换函数sin或log等的参数。如果你需要更准确的,请使用preg_replace