Amran Amran - 2 months ago 6
PHP Question

PHP - Replace String on Array

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?

Answer

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'