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.
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;
}
?>
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);
?>
If your split character is just "*" you can use explode:
$words = explode('*', $string, 2);
If it's "*" or "^" do this:
$words = preg_split("/[\*,\^]+/", $str, -1, PREG_SPLIT_NO_EMPTY);
If i am grasping true meaning of the question, OP mentioned
I have a string ending with '*' or '^'.
If you want to split the string in this way, you should change the regexp like this.
$words = preg_split("/[\*|\^]/", $variable, 2, PREG_SPLIT_NO_EMPTY);
This would break the string on first concurrence of * or ^. OP has already excepted an answer, but i am adding mine in case it helps anyone else in this situation.
Edit: You do not need to use preg_split() if you wanna do this. Simply use strstr with a few conditions.
$variable = 'abcd@ ef*';
if ( strpos( $variable, '*' ) < strpos( $variable, '^' ) || strpos( $variable, '^' ) === false )
{
$first = strstr($variable, '*', true);
$last = strstr($variable, '*');
}
if ( strpos( $variable, '^' ) < strpos( $variable, '*' ) || strpos( $variable, '*' ) === false )
{
$first = strstr($variable, '^', true);
$last = strstr($variable, '^');
}
echo $first;
echo '<br/>';
echo $last;
This one is working on every case.