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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split a string

Status
Not open for further replies.

hisham

IS-IT--Management
Nov 6, 2000
194
0
0
I have the following series of strings ie:
$str = "7hi"
or
$str = "15hello";
my question: how to print :
" this is 15 and hello "

I tried :
Code:
<?
$str = "15hello";
$results = preg_split('/^[0-9]+/', $str);
echo "this is $results[0] and $results[1]";
?>
but it wont print $results[0] as 15 !! it just prints hello

Thanks in advance.

 
I think the problem you are having with the preg_split is that your expression is looking to exclude the numbers (by having the ^[0-9] definition. Preg will see any number as the delimiter and only spit back your alphabetic responses. Therefore, if $str="1hello5there6" then $results[0]='hello' and $results[1]='there'.

I would think that you would be better to have a delimiter. Otherwise, you may need to do 2 preg_split, one to get the number and the other the text.

Hope this helps,
- flub
 
Code:
$text = '15hello';
preg_match('/^([0-9])*([a-z])*/i', $matches);
echo "this is $matches[1] and $matches[2]";

 
This fact that you have no delimiter seems to be causing some trouble. This would work, but involves a couple of extra steps so may not be practical depending on the performance you need.

Code:
$str = "15hello";
$boundary = ereg('[0-9]+', $str);
echo "$boundary<br>";
echo (substr($str, 0, $boundary + 1) . "<br>");
echo (substr($str, $boundary + 1) . "<br>");

Hope this helps
- flub
 
Thank you all,
Now I use this code for non Latin text:

Code:
<?
$text = "632YourNonLatinText";
preg_match('/^([0-9]+)*([^.]+)*/i',$text,$matches);
echo "this is $matches[1] and $matches[2]";
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top