Sort a text string by last word before separator
| From: | Andre Dubuc | Date: | Thu, 24 Jun 2004 03:38:00 +0000 |
| Subject: | Sort a text string by last word before separator | ||
| Groups: | php.general php.general | ||
| Request: | Send a blank email to php-general+get-188926@lists.php.net to get a copy of this message | ||
Given a text string:
$OK = "Joe Blow, William Howard Anser, Hannie Jansen, etc, etc,";
$_SESSION['txt'] = "$OK";
session_write_close();
$txt = $_SESSION['txt'];
$sorted = explode(", ", $txt);
sort($sorted);
print "$sorted";
results in a sort based on the first name:
"Hannie Jansen, Joe Blow, William Howard Anser, etc, etc"
I tried a another function (before_last)
******
function before ($this, $inthat)
{
return substr($inthat, 0, strpos($inthat, $this));
}
function strrevpos($instr, $needle)
{
$rev_pos = strpos (strrev($instr), strrev($needle));
if ($rev_pos===false) return false;
else return strlen($instr) - $rev_pos - strlen($needle);
};
function after_last ($this, $inthat)
{
if (!is_bool(strrevpos($inthat, $this)))
return substr($inthat, strrevpos($inthat, $this)+strlen($this));
};
function before_last ($this, $inthat)
{
return substr($inthat, 0, strrevpos($inthat, $this));
};
********
to sort on last name, and it does work, but gives only the last item:
$test2 = between_last(' ', ', ', $OK);
print "$test2";
"Jansen"
How would I get this 'before_last' function to iterate through the initial
string, so I could build a sorted list with both first and last names, sorted
by last name? I can't seem to get a proper 'foreach' statement to work, nor a
'while' statement.
I'm really confused. I've read almost every entry on arrays/strings and
searched code snippets. Almost all focus on one element arrays such "apple,
orange, peach" rather than 2 or more elements such as "fancy cars, big
trucks, fast dangerous motorcycles,"
Is it even possible to accomplish this type sort on a string?
Any advice, pointers, or help will be greatly appreciated,
Tia,
Andre