D
D
Dimas1232014-10-02 10:22:38
PHP
Dimas123, 2014-10-02 10:22:38

How to check for the presence of a substring and return the part of the string without that substring?

There is an array

$array = array('1', 'red', 'user_id_17'=>'Иван', '8',  'user_id_45'=>'Петр');

/*мне нужно получить массив array( '17'=>'Иван', '45'=>'Петр'), 
т.е. найти все ключи, начинающиеся на user_id_ и вернуть число после этой подстроки.
 Я могу его получить как-то так, но мне кажется это коряво: */

foreach($array as $key => $value){
if(substr_count($key, 'user_id_') > 0) {
$new_key = preg_replace("/\D/","","$key");
$new_array[$new_key] = $value;
}
}

If necessary, "user_id_" can be renamed differently.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2014-10-02
@Dimas123

str_replace to empty string?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question