Using PHP Replace SPACES in URLS with

后端 未结 6 1889
太阳男子
太阳男子 2020-11-27 18:46

I\'m looking to replace all instances of spaces in urls with %20. How would I do that with regex?

Thank you!

6条回答
  •  余生分开走
    2020-11-27 19:25

    You've got several options how to do this, either:

    • urlencode() or rawurlencode() - functions designed to encode URLs for http protocol
    • str_replace() - "heavy machinery" string replace
    • strtr() - would have better performance than str_replace() when replacing multiple characters
    • preg_replace() use regular expressions (perl compatible)

    strtr()

    Assuming that you want to replace "\t" and " " with "%20":

    $replace_pairs = array(
      "\t" => '%20',
      " " => '%20',
    );
    return strtr( $text, $replace_pairs)
    

    preg_replace()

    You've got few options here, either replacing just space ~ ~, again replacing space and tab ~[ \t]~ or all kinds of spaces ~\s~:

    return preg_replace( '~\s~', '%20', $text);
    

    Or when you need to replace string like this "\t \t \t \t" with just one %20:

    return preg_replace( '~\s+~', '%20', $text);
    

    I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space ( )

提交回复
热议问题