dongshao1021 2017-03-11 07:02
浏览 86

使用PHP转义字符串中的所有特殊字符

I want to escape all special characters from the input string for processing shell command. After that given string should be saved in DataBase.

In PHP I tried to escape all using the following code,

$pattern = "/[_a-z0-9-]/i";
    $new_content = '';
    $content = 'My new string with symbols ₹~`!@#$%^&*()_+|{}<?>":[];/.,';
    for($i = 0; $i < strlen($content); $i++) {
        //if you found the 'special character' then add the \
        if(!preg_match($pattern, $content[$i])) {
            $new_content .= '\\' . $content[$i];
            }
        else {
        //if there is no 'special character' then use the character
            $new_content .= $content[$i];
        }
        }

    $keyvalue[1] = $new_content;

NOTE:

I set shell to support UTF-8 characters If I type rupee symbol using keyboard my PHP not recognizing it and shows symbol like this.. at the end I get a string with missed characters.

Shell command is used here to send a response from PHP to Python

I am using Linux system with PHP v 5.5.9

Please let me know your ideas :)

  • 写回答

1条回答 默认 最新

  • duanaoou4105 2017-03-11 07:29
    关注

    I would do something like:

    <?php
    $pattern = "/[^_a-z0-9- ]/i";
    
     $content = 'My new string with symbols ₹~`!@#$%^&*()_+|{}<?>":[];/.,';
     $newcontent = preg_replace($pattern,'',$content);
     echo $newcontent;
    

    Prints:

    My new string with symbols _

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据