Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression

Status
Not open for further replies.

fonny

MIS
Joined
Jun 25, 2004
Messages
1
Location
GB
there is a variable

$name = "Smith,John";

how can we use a regular expression to swap round the names? to become John Smith?

Thank you
 
Assuming that the format of the name is "lastname,firstname":

echo preg_replace ('/([^,]*),(.*)/', '$2 $1', 'Smith,John');

should do it.



Want the best answers? Ask the best questions!

TANSTAAFL!!
 
The more I think about it, the more I think that the resource overhead of a regular expression engine is contraindicated here.

For something this simple, explode() would probably be better:

<?php
list ($last, $first) = explode (',', 'Smith,John');
echo $first . ' ' . $last;
?>



Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Some benchmarking (Laziness means I only timed it to the second). Shows explode is significantly faster.

[ul]
[li]100,000 replaces
[ul]
[li] Regex: 3 seconds [/li]
[li] explode: 1 second[/li]
[/ul]
[/li]
[li]1,000,000 replaces
[ul]
[li] Regex: 22 seconds[/li]
[li] explode: 18 seconds[/li]
[/ul]
[/li]
[li]10,000,000 replaces
[ul]
[li] Regex: 237 seconds[/li]
[li] explode: 176 seconds[/li]
[/ul]
[/li]
[/ul]

*Disclaimer... non-scientific, server had other loads while processing, but tests were run multiple times so it's certainlly good enough for a guide.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top