2

I have a string of values that are trailed by carets and groups of words are separated by semicolons.

I tried to split the string on semicolons, but I only want the first word after each semicolon without its trailing caret.

$myString = "apple^;ball^room^mouse^bat^;cricket^news^man^";
$myArray = explode(';', $myString);
print_r($myArray);

I want output from above string as below in single variable:

apple ball cricket

means first character befor caret sign of each semicolon

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

0

With the use of some PHP string and array manipulation functions you can do this

$myString = "apple^;ball^room^mouse^bat^;cricket^news^man^";
$myArray = explode(';', $myString);

foreach ($myArray as &$a) {
    $p = strpos($a, '^');
    $a = substr($a,0,$p);
}
$str = implode(' ', $myArray);

echo 'Input was > ' . $myString . PHP_EOL;
echo 'Output is > ' . $str . PHP_EOL;

RESULT

Input was > apple^;ball^room^mouse^bat^;cricket^news^man^
Output is > apple ball cricket
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

Split your string from every ^ character until the next occurring ; (or the end of the string). PREG_SPLIT_NO_EMPTY() will ensure that no empty elements are generated while exploding.

Code: (Demo)

$myString = "apple^;ball^room^mouse^bat^;cricket^news^man^";

var_export(implode(' ', preg_split('/\^[^;]*;?/', $myString, 0, PREG_SPLIT_NO_EMPTY)));

Output:

'apple ball cricket'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136