How to generate a set of arrays from a string in php

This is my line

#Jhon: Manager #Mac: Project Manager #Az: Owner

And I need an array like this

$array = ['0' => 'Manager', '1' => 'Project Manager', '2' => 'Owner']

I tried this, but every time I return only the "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;
  }
} 
+4
source share
4 answers

You can preg_splitcontent 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 a demo of PHP and a demo version of regex .

Template Details :

  • \s* - spaces 0+
  • # - letter #
  • [^:]+ to match 1+ characters other than :
  • : - colon
  • \s* - 0+ spaces.

, -1 preg_split function $limit, PHP, ( ) PREG_SPLIT_NO_EMPTY ( , , , ).

+8

preg_match .

Regex: #\w+\s*\:\s*\K[\w\s]+

1. #\w+\s*\:\s*\K #, words, spaces, : \K reset.

2. [\w\s]+ , words spaces.

1:

<?php
ini_set('display_errors', 1);
$string="#Jhon: Manager #Mac: Project Manager #Az: Owner";
preg_match_all("/#\w+\s*\:\s*\K[\w\s]+/", $string,$matches);
print_r($matches);

:

Array
(
    [0] => Array
        (
            [0] => Manager 
            [1] => Project Manager 
            [2] => Owner
        )

)


array_map explode . exploding string #, : first .

2:

<?php

$string="#Jhon: Manager #Mac: Project Manager #Az: Owner";
$result=  array_map(function($value){
    return trim(explode(":",$value)[1]);
}, array_filter(explode("#", $string)));
print_r(array_filter($result));

:

Array
(
    [1] => Manager
    [2] => Project Manager
    [3] => Owner
)
+6

You can use explode () to split the string into char. After that, just replace the elements of the new preg_replace () array .

0
source

try it

$string = '#Jhon: Manager #Mac: Project Manager #Az: Owner';
$res = explode("#", $string);
$result = array();
for($i = 1; $i < count($res); $i++)  {
    $result[] = preg_replace("/(^[A-Z][a-z]*: )/", "", $res[$i]);
}
0
source

Source: https://habr.com/ru/post/1676467/


All Articles