I'm trying to use preg_replace to remove everytihng from a string except letters and the apostrophe. The following code results in whos, instead of who's. Would someone please explain my mistake? $text = "who's"; $text = preg_replace("/[^a-zA-Z']/", "", $text); PHP:
try escaping the apos with backslash \ so $text = "who's"; $text = preg_replace("/[^a-zA-Z\']/", "", $text);
If you were only stripping them for security or something, then use addslashes() and stripslashes().. $text = "who's"; $text = addslashes($text); // turns "who's" into "who\'s" $text = preg_replace("/[^a-zA-Z\]/", "", $text); PHP: then echo stripslashes($text); and it'll return "who's" without breaking any code.
No, it's not for security. The original text can contain any character but the useable (resulting) text can only contain letters and the apostrophe since, without it, the word is incorrect. I tried your example though but it failed with "Compilation failed: missing terminating ]." I assume you meant [^a-zA-Z\!] so I tried that but the result is the same - the apostrophe gets removed.
oops my mistake. I was confusing the ` (apostrophe) symbol with the single quote ( ' ) So this does work $text = "who's"; $text = preg_replace("/[^a-zA-Z\']/", "", $text); echo $text; But if you are also confusing the two, and there is another problem then lemme know
The actual problem turned out to be how the text was stored in the database. The apostrophe was being stored as ' instead of '. So I add this code and everything is working now $text = str_replace("'", "'", $text); PHP: I appreciate the help. It showed me my initial assumption was incorrect and allowed me to get to the actaul problem. Thank you both.
Glad you figured it out Often the input of other people (even if it's incorrect input) can help your mind stumble upon the right answer! Good luck with the rest! Chuckun