replace text without function

2019-07-27 16:09发布

问题:

I've a php question. I've a php code, it prints some long texts. I want replace "n" character in output text with "N". I can create a function. but I can't (and don't like!) put my text to a function (because I have many texts!). Is there any way to replace "n" with "N" without any function???

Thanks ..

回答1:

No need to create a function, just use str_replace, the built in function for this purpose like this:

$output_text = str_replace('n', 'N', $input_text);
echo $output_text;

[EDIT] If you don't want to put your text in a function, because there is lots of text (as you say), do it like this:

<?php
 ob_start();

 //..... ALL YOUR CODE GOES HERE

 $FullOutput = ob_get_clean();
 echo str_replace('n', 'N', $FullOutput);
?>

This effectively buffers (catches and stores) all your output and at the end get's it and replaces the 'n' to 'N' and echoes it.



回答2:

<?php
   $newString = str_replace('n','N',$oldString);
?>


回答3:

str_replace lets you do replacements such as you need. It can also accept multiple find/replace pairs at once, which lets you define these pairs at a central location in your code:

$replacements = array(
    'n' => 'N',
    'foo' => 'bar',
    // as many others as you want
)

// At some other point:
$input = str_replace(
    array_keys($replacements),
    array_values($replacements),
    $output);