Search code examples
phpexplodepreg-split

PHP Regular expression 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 can't find one.


Solution

  • Thank you for all your answers.
    I have figured my solution by the references you all given.
    I am posting it,May help anyone in future..

    <?php
    
    $variable = 'Chloride TDS';
    if (preg_match('/[\*^]/', $variable))
    {
    if ( strpos( $variable, '*' ) < strpos( $variable, '^' )   || strpos( $variable, '^' ) === false ) 
    {
        $first = strstr($variable, '*', true);
    
        $last = strstr($variable, '*');
    }
    
    if ( strpos( $variable, '^' ) < strpos( $variable, '*' ) && strpos($variable,'^') != '' || strpos( $variable, '*' ) === false ) 
    {
        $first = strstr($variable, '^', true);
        $last = strstr($variable, '^');
    }
    echo $first;
    echo '<br/>';
    echo $last;
    }else{
        echo $variable;
    }
    
    
    
    ?>