PHP - 替换Array上的String

PHP  - 替换Array上的String

问题描述:

I want to make a String Replace on a variable that user input. May I know how do I want it to accept (') on the string. Let say for example,

$string = ' *this* is 'a' test' ';
$regexes = array('/~(.*?)~/six','/\*(.*?)\*/six'); 
$replaces = array('<i>$1</i>','<b>$1</b>');
$new_string = preg_replace($regexes, $replaces, $string);   

echo $new_string;

I can make it to change to bold and italic text but if the string has ' '' ', it will give an error. How do I want to accomplish this?

This may help you, use addslashes and stripslashes as required.

<?php
$string = " *this* is 'a' test' ";
$string = addslashes($string);
$regexes = array('/~(.*?)~/six','/\*(.*?)\*/six'); 
$replaces = array('<i>$1</i>','<b>$1</b>');
$new_string = preg_replace($regexes, $replaces, $string);   
echo stripslashes($new_string);
?>

This Outputs: this is 'a' test'