Mohammed Iqbal Khan Mohammed Iqbal Khan - 26 days ago 8
PHP Question

PHP Regular expresion for star '*'

I have a string ending with '*' or '^'.

For example :

$variable = 'abcdef**^^';


I used preg_split() function to split the string.

$variable = 'abcdef*^^^^';
$words = preg_split("/(?<=\w)\b[!?.]*/", $variable, -1, PREG_SPLIT_NO_EMPTY);


And I got the output as

Array
(
[0] => abcdef
[1] => *^^^^
)


But the problem begins, when my variable is replaced with '@','' and some other special characters.

For Example:

$variable = 'abc@d ef*^^^';


Output become like this

Array
(
[0] => abcd
[1] => @ ef
[2] => *^^^^
)


I need the output like this

Array
(
[0] => abcd@ ef
[1] => *^^^^
)


I was trying to replace my current RegEx with RegEx for '*' and '^',But I cant find one.Can any one help me with this.

Answer Source

use \* for star. below are the example

<?php

$variable = 'abc@d ef*^^^';
$words = preg_split("/\*/", $variable, -1, PREG_SPLIT_NO_EMPTY);
echo "<pre>";
print_r($words);  
?>

and it's output is this

Array
(
    [0] => abc@d ef
    [1] => ^^^
)

if you want to add * then used this

<?php

$variable = 'abc@d ef*^^^';
$words = preg_split("/\*/", $variable, -1, PREG_SPLIT_NO_EMPTY);

$i=0;  
foreach ($words as $value) {
    if($i != 0)
    {
        $words[$i]='*'.$words[$i];
    }
    $i++;
}

echo "<pre>";
print_r($words);
?>