Trying to separate a name and phone number from a string

I am trying to separate a name and phone number from a string

$string = “Jim Brown - 07000 000000”;
$string = “Jim Brown, 07000 000000”;
$string = “Jim Brown 07000 000000”;

The format could be any of the above.

I would simply like to return the name and phone number seperately.

I have created a lengthy str_replace function., but I bet there’s a much more elegant and reliable method.

Thanks.

I would guess you could use explode() on the first and second examples.

You could use explode on the last example if you were sure that it was always the same format.


<?php
$cases = array(
	'Jim Brown, 07000 000000',
	'Jim Brown - 07000 000000',
	'Jim Brown, 07000 000000',
);


foreach($cases as $case)
{
	preg_match_all('~[a-z0-9]+~i', $case, $matches);
	
	if(4 !== count($matches[0])){
		continue;
	}


	list($fname, $sname, $prefix, $number) = $matches[0];


	echo "Forename: $fname, Surname: $sname ($prefix) $number", PHP_EOL;
}


/*
	Forename: Jim, Surname: Brown (07000) 000000
	Forename: Jim, Surname: Brown (07000) 000000
	Forename: Jim, Surname: Brown (07000) 000000
*/

My first attemp:



defined('jj') ? NULL : define('jj', '<br />') ;     	

$a = array
(
  "Jim Brown - 07000 000000",
  "Jim Brown, 07000 000000",
  "Jim Brown 07000 000000",
);

foreach( $a as $aa):
	
	# replace - and ,
	$bb = str_replace(array('-',',') , ' ', $aa); 

	# extract from start up until first occurrence of ' 0'
	$cc = substr( $bb, 0, strpos($bb, ' 0') );

	# extract remainder	starting from ' 0'
	$dd = substr( $bb, strpos($bb, ' 0') );

	echo jj,  '$aa = "' ,   $aa   .'"';
	echo jj,  '$bb = "' ,   $bb   .'"';
	echo jj,  '$cc = "' ,   $cc    .'"';
	echo jj,  '$dd = "' ,   $dd   .'"';
	echo jj,jj;

endforeach;	
    	
# Output:

$aa = "Jim Brown - 07000 000000"
$bb = "Jim Brown 07000 000000"
$cc = "Jim Brown"
$dd = " 07000 000000"

$aa = "Jim Brown, 07000 000000"
$bb = "Jim Brown 07000 000000"
$cc = "Jim Brown"
$dd = " 07000 000000"

$aa = "Jim Brown 07000 000000"
$bb = "Jim Brown 07000 000000"
$cc = "Jim Brown"
$dd = " 07000 000000"