How to generate set of array from string in php

php, regex

Solution

You may `preg_split` the contents and use the following solution:

$re = '/\s*#[^:]+:\s*/';
$str = '#Jhon: Manager #Mac: Project Manager #Az: Owner';
$res = preg_split($re, $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($res);

See the PHP demo and a regex demo.

Pattern details:

- `\s*` - 0+ whitespaces

- `#` - a literal `#` symbol

- `[^:]+` to match 1+ chars other than `:`

- `:` - a colon

- `\s*` - 0+ whitespaces.

Note that `-1` in the `preg_split` function is the `$limit` argument telling PHP to split any amount of times (as necessary) and `PREG_SPLIT_NO_EMPTY` will discard all empty matches (this one may be removed if you need to keep empty matches, that depends on what you need to do further).

Problem

This is my string #Jhon: Manager #Mac: Project Manager #Az: Owner And I want array something like this ``` $array = ['0' => 'Manager', '1' => 'Project Manager', '2' => 'Owner'] ``` I tried this but each time return only 'Manager' ``` $string = '#Jhon: Manager #Mac: Project Manager #Az: Owner'; getText($string, ':', ' #') public function getText($string, $start, $end) { $pattern = sprintf( '/%s(.+?)%s/ims', preg_quote($start, '/'), preg_quote($end, '/') ); if (preg_match($pattern, $string, $matches)) { list(, $match) = $matches; echo $match; } } ```

Original source