prexPHP
prexPHP

Reputation: 23

How can I print text with spaces from array?

In this array I have user with her ID:

$data = array( 'USER : Alex K. id:1', 'USER : Robert K. id:2');

The name on the id 1 is "Alex K." and on the id 2 is

foreach ( $data as $string )
{
    $_a = explode( ':', $string );
    $_b = explode( ' ', $_a[1] );
    $inf[$_a[2]] = $_b[1];
}

If i use print_r( $inf[ID] ); for example print_r( $inf[2] ); this show me only "Robert" but no "Robert K.";

I try with print_r( $_b ); and I get all data buy I donw know how print the complete name.

Someone know how do it?

Upvotes: 1

Views: 339

Answers (2)

mickmackusa
mickmackusa

Reputation: 48100

If you don't plan on performing any other searches on the input array, then you don't need to generate a new, re-structured, associative lookup array.

preg_filter() will find your user by id and isolate the user name in one step.

Code: (Demo) (or if users may have colons in their names)

$data = ['USER : Alex K. id:1', 'USER : Robert K. id:2'];
$id = 2;
var_export(current(preg_filter('/USER : ([^:]*) id:' . $id . '$/', '$1', $data)));

Output:

'Robert K.'

preg_filter() will iterate all of the elements and try to modify them, but since the $id variable at the end of the pattern will only allow one of the elements to be matched/modified, it will be the only element in the returned data.

current() will grab the first/only element if there is one. If there is no match, then the output will be false.

I am using var_export() to show that there are no leading or trailing spaces -- you can use echo just the same.

Upvotes: 1

Mike Doe
Mike Doe

Reputation: 17634

If the format of the array's members is always the same, you can simply grab specific parts of the string, eg. using preg_match:

foreach ($data as $string) {
    preg_match('/USER : (?<name>.*?) id:(?<id>\d+)/', $string, $match);

    printf('User: %s. His ID: %d', $match['name'], $match['id']);
}

Otherwise you have to "clean" the input string before exploding it by a "space" – by removing the noise, things you don't need, like the USER : part (functions which may come in handy: str_replace / substr etc.)

If you need to somehow manipulate this list, you would have to index it first, eg. by the id:

$users = [];

foreach ($data as $string) {
    preg_match('/USER : (?<name>.*?) id:(?<id>\d+)/', $string, $match);

    $users[$match['id']] = $match['name'];
}

printf('User name with ID 1 is: %s', $users[1]);

Upvotes: 2

Related Questions