当前位置: 动力学知识库 > 问答 > 编程问答 >

Breaking a php string into multiple strings

问题描述:

I am trying to break up a string in php, the string is created as follows

 $users = shell_exec("ldapsearch -h ldap01 -p xxx -x -b 'dc=xxxxx,dc=com' '(cn=xxxx*)' | grep uid | grep -v xxxxx | grep -v xxxxxx | grep -v xxxxx | awk {'print $2'} | cut -d ',' -f 1 | cut -c 5-30");

The string then returns a bunch of names, which i want to compare to something a user enters into a form in another part of the page. If I print the $users variable I get the list of names but it is all one long string not the individual names.

I tried using strtok or explode but nothing seems to work. I have the following.

 $names = explode(" ", $users);

But when i print that it just prints the word array and thats it. I tried strtok and tried looping through the names but when I do I only get the first letter of the first name. the names are separated by spaces when they are printed out if that helps. Im sure im missing something simple but any help is appreciated.

UPDATE:

No such luck (thanks for all the responses so far). I tried exploding again

 $users = shell_exec("ldapsearch -h ldap01 -p 389 -x -b 'dc=mlbam,dc=com' '(cn=Systems*)' | grep uid | grep -v rtfortrac | grep -v mlbnsinfo | grep -v sysweb | awk {'print $2'} | cut -d ',' -f 1 | cut -c 5-30");

#$names = $users;

$names = explode(" ", $users);

print_r($names);

When I run this my output is all the names (x'd out here) in one string. I need these to be separated so that I can check the user's input against them.

 Array ( [0] => xxxx xxxxxxx xxxxxx xxxxx xxxxxx xxxxxx etc )

If I uncomment the $names = $users; and get the length of the string it returns 135

 $length = strlen($names);

网友答案:

But when i print that it just prints the word array and thats it.

It is an array so normal echo or print won't work.

Make use of print_r($users) or var_dump($users);

<?php
$names = explode(" ", $users);
print_r($names);
网友答案:

Try this:

<?php

$names = explode(" ", $users);

echo '<pre>';
print_r($names);

?>

or

<?php

$names = explode(" ", $users);

var_dumb($names);

?>
  • Thanks
网友答案:

I want to thank everybody for the help, but I believe I solved my problem. When I use preg_split like so

    $names = preg_split("/[\s,]+/", $users);

    print_r($names);

The output is what I am looking for.

    Array ( [0] => xxxxx [1] => xxxxx [2] => xxxxx [3] => xxxx [4] => xxxxx [5] => xxxx [6] => xxxx [7] => etc )

So this can be considered solved for me. I found the solution after some additional digging here

http://php.net/manual/en/function.preg-split.php

Thanks again all.

分享给朋友:
您可能感兴趣的文章:
随机阅读: