Home>

I would like to replace a string.
If there are multiple candidates and there is one of them, I would like to replace it with the target character.
I don't know the corresponding function.

I think it is possible by repeating str_replace as shown below, but is there a function that can perform this process all at once?

$text = "ABCDEFG";
$convertWords = [
    "B",
    "C",
    "F"
];;
foreach ($convertWords as $word) {
    $text = str_replace ($word, "*", $text);
}
var_dump ($text);
// A ** DE * G
php
  • Answer # 1

    You can pass an array as the first argument of str_replace ().

    (php.net) str_replace

    <? php
    $text = "ABCDEFG";
    $convertWords = [
        "B",
        "C",
        "F"
    ];;
    $text = str_replace ($convertWords, "*", $text);
    var_dump ($text);


    Result

    $php test.php
    string (7) "A ** DE * G"

  • Answer # 2

    Is it possible to use preg_replace?

  • Answer # 3

    $pattern = "/ (". Implode ("|", array_map) {return preg_quote ($x);}, $convertWords)). ") /";
    $replacement = "*";
    print preg_replace ($pattern, $replacement, $text);

Related articles