0
votes

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
why don't you do preg replace all characters that don't match that?apokryfos

1 Answers

0
votes

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 _