Split words only if last letter matches a specific char

47 Views Asked by At

I am using this php function in order to split the array as soon a ":" is used:

$headline = 'Lorem ipsum: dolor sit amet, consectetuer adipiscing elit';
var_dump( explode( ':', $headline ) );

I need to modify the code so that if the ":" is within a word, it doesn't explode, for example:

$headline = 'Lorem:ipsum: dolor sit amet, consectetuer adipiscing elit';
var_dump( explode( ':', $headline ) );

Desired Result:

Lorem:ipsum:
dolor sit amet, consectetuer adipiscing elit

So it should only explode if the : is at the end of a word. Thanks for any help!

I've tried it by using if (\str_ends_with but with no success (I'm a PHP noob).

1

There are 1 best solutions below

3
user2342558 On BEST ANSWER

To achieve that you can use the preg_split PHP function that uses a regex as delimiter:

$headline = 'Lorem:ipsum: dolor sit amet, consectetuer adipiscing elit';
print_r(preg_split("/:[^\w]/", $headline));

The regex :[^\w] means "a : not followed by a word character".

Output:

Array
(
    [0] => Lorem:ipsum
    [1] => dolor sit amet, consectetuer adipiscing elit
)

Try it here https://onlinephp.io/c/64e18