Str_replace for multiple items












79















I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters /:*?"<>|, without doing a str_replace for each.










share|improve this question


















  • 1





    you want to replace all these chars with a space?

    – Book Of Zeus
    Sep 30 '11 at 2:53






  • 7





    Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

    – Mike B
    Sep 30 '11 at 2:57


















79















I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters /:*?"<>|, without doing a str_replace for each.










share|improve this question


















  • 1





    you want to replace all these chars with a space?

    – Book Of Zeus
    Sep 30 '11 at 2:53






  • 7





    Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

    – Mike B
    Sep 30 '11 at 2:57
















79












79








79


18






I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters /:*?"<>|, without doing a str_replace for each.










share|improve this question














I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters /:*?"<>|, without doing a str_replace for each.







php string str-replace






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 30 '11 at 2:51









sameoldsameold

5,937164779




5,937164779








  • 1





    you want to replace all these chars with a space?

    – Book Of Zeus
    Sep 30 '11 at 2:53






  • 7





    Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

    – Mike B
    Sep 30 '11 at 2:57
















  • 1





    you want to replace all these chars with a space?

    – Book Of Zeus
    Sep 30 '11 at 2:53






  • 7





    Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

    – Mike B
    Sep 30 '11 at 2:57










1




1





you want to replace all these chars with a space?

– Book Of Zeus
Sep 30 '11 at 2:53





you want to replace all these chars with a space?

– Book Of Zeus
Sep 30 '11 at 2:53




7




7





Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

– Mike B
Sep 30 '11 at 2:57







Don't be afraid to reference the excellent php.net manual and review the params section to see if what you want is possible.

– Mike B
Sep 30 '11 at 2:57














8 Answers
8






active

oldest

votes


















85














str_replace() can take an array, so you could do:



$new_str = str_replace(str_split('\/:*?"<>|'), ' ', $string);


Alternatively you could use preg_replace():



$new_str = preg_replace('~[\\/:*?"<>|]~', ' ', $string);





share|improve this answer





















  • 2





    Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

    – GreenMatt
    Sep 30 '11 at 4:13













  • @GreenMatt You are right.

    – NullUserException
    Sep 30 '11 at 4:26











  • Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

    – Bradmage
    Dec 31 '15 at 23:13





















141














Like this:



str_replace(array(':', '\', '/', '*'), ' ', $string);


Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:



str_replace([':', '\', '/', '*'], ' ', $string);





share|improve this answer

































    51














    For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:



    print str_replace(
    array("search1","search2"),
    array("replace1", "replace2"),
    "search1 search2"
    );



    // Output: replace1 replace2







    share|improve this answer































      41














      str_replace(
      array("search","items"),
      array("replace", "items"),
      $string
      );





      share|improve this answer































        6














        If you're only replacing single characters, you should use strtr()






        share|improve this answer



















        • 1





          Single characters only? How come?

          – Jimmy Kane
          Jul 31 '14 at 13:41



















        1














        You could use preg_replace(). The following example can be run using command line php:



        <?php
        $s1 = "the string \/:*?"<>|";
        $s2 = preg_replace("^[\\/:*?"<>|]^", " ", $s1) ;
        echo "n$s2: "" . $s2 . ""n";
        ?>


        Output:




        $s2: "the string          "







        share|improve this answer


























        • Too much escaping inside the character class. (see accepted answer)

          – mickmackusa
          Apr 21 '18 at 6:31



















        0














        I guess you are looking after this:



        // example
        private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

        ...

        public function templateFor(string $type, string $language): string
        {
        return str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
        }





        share|improve this answer































          -1














          I had a situation whereby I had to replace the HTML tags with two different replacement results.



          $trades = "<li>Sprinkler and Fire      Protection Installer</li>
          <li>Steamfitter </li>
          <li>Terrazzo, Tile and Marble Setter</li>";

          $s1 = str_replace('<li>', '"', $trades);

          $s2 = str_replace('</li>', '",', $s1);

          echo $s2;


          result



          "Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7605480%2fstr-replace-for-multiple-items%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            85














            str_replace() can take an array, so you could do:



            $new_str = str_replace(str_split('\/:*?"<>|'), ' ', $string);


            Alternatively you could use preg_replace():



            $new_str = preg_replace('~[\\/:*?"<>|]~', ' ', $string);





            share|improve this answer





















            • 2





              Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

              – GreenMatt
              Sep 30 '11 at 4:13













            • @GreenMatt You are right.

              – NullUserException
              Sep 30 '11 at 4:26











            • Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

              – Bradmage
              Dec 31 '15 at 23:13


















            85














            str_replace() can take an array, so you could do:



            $new_str = str_replace(str_split('\/:*?"<>|'), ' ', $string);


            Alternatively you could use preg_replace():



            $new_str = preg_replace('~[\\/:*?"<>|]~', ' ', $string);





            share|improve this answer





















            • 2





              Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

              – GreenMatt
              Sep 30 '11 at 4:13













            • @GreenMatt You are right.

              – NullUserException
              Sep 30 '11 at 4:26











            • Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

              – Bradmage
              Dec 31 '15 at 23:13
















            85












            85








            85







            str_replace() can take an array, so you could do:



            $new_str = str_replace(str_split('\/:*?"<>|'), ' ', $string);


            Alternatively you could use preg_replace():



            $new_str = preg_replace('~[\\/:*?"<>|]~', ' ', $string);





            share|improve this answer















            str_replace() can take an array, so you could do:



            $new_str = str_replace(str_split('\/:*?"<>|'), ' ', $string);


            Alternatively you could use preg_replace():



            $new_str = preg_replace('~[\\/:*?"<>|]~', ' ', $string);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 30 '11 at 4:26

























            answered Sep 30 '11 at 2:54









            NullUserExceptionNullUserException

            65.5k22176214




            65.5k22176214








            • 2





              Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

              – GreenMatt
              Sep 30 '11 at 4:13













            • @GreenMatt You are right.

              – NullUserException
              Sep 30 '11 at 4:26











            • Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

              – Bradmage
              Dec 31 '15 at 23:13
















            • 2





              Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

              – GreenMatt
              Sep 30 '11 at 4:13













            • @GreenMatt You are right.

              – NullUserException
              Sep 30 '11 at 4:26











            • Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

              – Bradmage
              Dec 31 '15 at 23:13










            2




            2





            Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

            – GreenMatt
            Sep 30 '11 at 4:13







            Assuming the OP meant that the backslash should be replaced, that preg_replace pattern didn't work for me. To get the backslash to work as expected, I had to use 4 of them (i.e. "\\") in the pattern.

            – GreenMatt
            Sep 30 '11 at 4:13















            @GreenMatt You are right.

            – NullUserException
            Sep 30 '11 at 4:26





            @GreenMatt You are right.

            – NullUserException
            Sep 30 '11 at 4:26













            Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

            – Bradmage
            Dec 31 '15 at 23:13







            Good answer, adding @dogbert answer in would make it complete for the people who don't read the manual and don't realise str_split returns an array.

            – Bradmage
            Dec 31 '15 at 23:13















            141














            Like this:



            str_replace(array(':', '\', '/', '*'), ' ', $string);


            Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:



            str_replace([':', '\', '/', '*'], ' ', $string);





            share|improve this answer






























              141














              Like this:



              str_replace(array(':', '\', '/', '*'), ' ', $string);


              Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:



              str_replace([':', '\', '/', '*'], ' ', $string);





              share|improve this answer




























                141












                141








                141







                Like this:



                str_replace(array(':', '\', '/', '*'), ' ', $string);


                Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:



                str_replace([':', '\', '/', '*'], ' ', $string);





                share|improve this answer















                Like this:



                str_replace(array(':', '\', '/', '*'), ' ', $string);


                Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:



                str_replace([':', '\', '/', '*'], ' ', $string);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 23 '16 at 17:07









                Codemonkey

                1,61822241




                1,61822241










                answered Sep 30 '11 at 2:53









                DogbertDogbert

                152k28240265




                152k28240265























                    51














                    For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:



                    print str_replace(
                    array("search1","search2"),
                    array("replace1", "replace2"),
                    "search1 search2"
                    );



                    // Output: replace1 replace2







                    share|improve this answer




























                      51














                      For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:



                      print str_replace(
                      array("search1","search2"),
                      array("replace1", "replace2"),
                      "search1 search2"
                      );



                      // Output: replace1 replace2







                      share|improve this answer


























                        51












                        51








                        51







                        For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:



                        print str_replace(
                        array("search1","search2"),
                        array("replace1", "replace2"),
                        "search1 search2"
                        );



                        // Output: replace1 replace2







                        share|improve this answer













                        For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:



                        print str_replace(
                        array("search1","search2"),
                        array("replace1", "replace2"),
                        "search1 search2"
                        );



                        // Output: replace1 replace2








                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Feb 10 '15 at 20:36









                        SumoanandSumoanand

                        7,24213741




                        7,24213741























                            41














                            str_replace(
                            array("search","items"),
                            array("replace", "items"),
                            $string
                            );





                            share|improve this answer




























                              41














                              str_replace(
                              array("search","items"),
                              array("replace", "items"),
                              $string
                              );





                              share|improve this answer


























                                41












                                41








                                41







                                str_replace(
                                array("search","items"),
                                array("replace", "items"),
                                $string
                                );





                                share|improve this answer













                                str_replace(
                                array("search","items"),
                                array("replace", "items"),
                                $string
                                );






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Sep 30 '11 at 2:54









                                MartyMarty

                                31k1874147




                                31k1874147























                                    6














                                    If you're only replacing single characters, you should use strtr()






                                    share|improve this answer



















                                    • 1





                                      Single characters only? How come?

                                      – Jimmy Kane
                                      Jul 31 '14 at 13:41
















                                    6














                                    If you're only replacing single characters, you should use strtr()






                                    share|improve this answer



















                                    • 1





                                      Single characters only? How come?

                                      – Jimmy Kane
                                      Jul 31 '14 at 13:41














                                    6












                                    6








                                    6







                                    If you're only replacing single characters, you should use strtr()






                                    share|improve this answer













                                    If you're only replacing single characters, you should use strtr()







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Sep 30 '11 at 3:05









                                    Explosion PillsExplosion Pills

                                    149k38226310




                                    149k38226310








                                    • 1





                                      Single characters only? How come?

                                      – Jimmy Kane
                                      Jul 31 '14 at 13:41














                                    • 1





                                      Single characters only? How come?

                                      – Jimmy Kane
                                      Jul 31 '14 at 13:41








                                    1




                                    1





                                    Single characters only? How come?

                                    – Jimmy Kane
                                    Jul 31 '14 at 13:41





                                    Single characters only? How come?

                                    – Jimmy Kane
                                    Jul 31 '14 at 13:41











                                    1














                                    You could use preg_replace(). The following example can be run using command line php:



                                    <?php
                                    $s1 = "the string \/:*?"<>|";
                                    $s2 = preg_replace("^[\\/:*?"<>|]^", " ", $s1) ;
                                    echo "n$s2: "" . $s2 . ""n";
                                    ?>


                                    Output:




                                    $s2: "the string          "







                                    share|improve this answer


























                                    • Too much escaping inside the character class. (see accepted answer)

                                      – mickmackusa
                                      Apr 21 '18 at 6:31
















                                    1














                                    You could use preg_replace(). The following example can be run using command line php:



                                    <?php
                                    $s1 = "the string \/:*?"<>|";
                                    $s2 = preg_replace("^[\\/:*?"<>|]^", " ", $s1) ;
                                    echo "n$s2: "" . $s2 . ""n";
                                    ?>


                                    Output:




                                    $s2: "the string          "







                                    share|improve this answer


























                                    • Too much escaping inside the character class. (see accepted answer)

                                      – mickmackusa
                                      Apr 21 '18 at 6:31














                                    1












                                    1








                                    1







                                    You could use preg_replace(). The following example can be run using command line php:



                                    <?php
                                    $s1 = "the string \/:*?"<>|";
                                    $s2 = preg_replace("^[\\/:*?"<>|]^", " ", $s1) ;
                                    echo "n$s2: "" . $s2 . ""n";
                                    ?>


                                    Output:




                                    $s2: "the string          "







                                    share|improve this answer















                                    You could use preg_replace(). The following example can be run using command line php:



                                    <?php
                                    $s1 = "the string \/:*?"<>|";
                                    $s2 = preg_replace("^[\\/:*?"<>|]^", " ", $s1) ;
                                    echo "n$s2: "" . $s2 . ""n";
                                    ?>


                                    Output:




                                    $s2: "the string          "








                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Sep 30 '11 at 4:08

























                                    answered Sep 30 '11 at 2:54









                                    GreenMattGreenMatt

                                    13.3k54269




                                    13.3k54269













                                    • Too much escaping inside the character class. (see accepted answer)

                                      – mickmackusa
                                      Apr 21 '18 at 6:31



















                                    • Too much escaping inside the character class. (see accepted answer)

                                      – mickmackusa
                                      Apr 21 '18 at 6:31

















                                    Too much escaping inside the character class. (see accepted answer)

                                    – mickmackusa
                                    Apr 21 '18 at 6:31





                                    Too much escaping inside the character class. (see accepted answer)

                                    – mickmackusa
                                    Apr 21 '18 at 6:31











                                    0














                                    I guess you are looking after this:



                                    // example
                                    private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

                                    ...

                                    public function templateFor(string $type, string $language): string
                                    {
                                    return str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
                                    }





                                    share|improve this answer




























                                      0














                                      I guess you are looking after this:



                                      // example
                                      private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

                                      ...

                                      public function templateFor(string $type, string $language): string
                                      {
                                      return str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
                                      }





                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        I guess you are looking after this:



                                        // example
                                        private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

                                        ...

                                        public function templateFor(string $type, string $language): string
                                        {
                                        return str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
                                        }





                                        share|improve this answer













                                        I guess you are looking after this:



                                        // example
                                        private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';

                                        ...

                                        public function templateFor(string $type, string $language): string
                                        {
                                        return str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Oct 2 '18 at 11:20









                                        Erald KarakashiErald Karakashi

                                        7114




                                        7114























                                            -1














                                            I had a situation whereby I had to replace the HTML tags with two different replacement results.



                                            $trades = "<li>Sprinkler and Fire      Protection Installer</li>
                                            <li>Steamfitter </li>
                                            <li>Terrazzo, Tile and Marble Setter</li>";

                                            $s1 = str_replace('<li>', '"', $trades);

                                            $s2 = str_replace('</li>', '",', $s1);

                                            echo $s2;


                                            result



                                            "Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",






                                            share|improve this answer




























                                              -1














                                              I had a situation whereby I had to replace the HTML tags with two different replacement results.



                                              $trades = "<li>Sprinkler and Fire      Protection Installer</li>
                                              <li>Steamfitter </li>
                                              <li>Terrazzo, Tile and Marble Setter</li>";

                                              $s1 = str_replace('<li>', '"', $trades);

                                              $s2 = str_replace('</li>', '",', $s1);

                                              echo $s2;


                                              result



                                              "Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",






                                              share|improve this answer


























                                                -1












                                                -1








                                                -1







                                                I had a situation whereby I had to replace the HTML tags with two different replacement results.



                                                $trades = "<li>Sprinkler and Fire      Protection Installer</li>
                                                <li>Steamfitter </li>
                                                <li>Terrazzo, Tile and Marble Setter</li>";

                                                $s1 = str_replace('<li>', '"', $trades);

                                                $s2 = str_replace('</li>', '",', $s1);

                                                echo $s2;


                                                result



                                                "Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",






                                                share|improve this answer













                                                I had a situation whereby I had to replace the HTML tags with two different replacement results.



                                                $trades = "<li>Sprinkler and Fire      Protection Installer</li>
                                                <li>Steamfitter </li>
                                                <li>Terrazzo, Tile and Marble Setter</li>";

                                                $s1 = str_replace('<li>', '"', $trades);

                                                $s2 = str_replace('</li>', '",', $s1);

                                                echo $s2;


                                                result



                                                "Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Feb 15 '17 at 18:19









                                                TemptehTempteh

                                                11




                                                11






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7605480%2fstr-replace-for-multiple-items%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Costa Masnaga

                                                    Fotorealismo

                                                    Sidney Franklin