...

Help

avelonx
07-18-2002, 04:46 AM
Could someone pleasse show me a piece of code of how to search a string for the first numerical value and return how many characters from the begininng it is
example:

"abcdefg4hi"

a = 0
b = 1
c = 2
d = 3
e = 4
f = 5
g = 6
4 = 7th characters from the beginning


so it would return 7

Cloudski
07-18-2002, 05:09 AM
Well, in C++, you would treat the string the same as an array.

So:


<?
$myString="abcdefg4hi";
for($i=0;$i<$myString.length();$i++)
{
if($myString[$i]>=0 && $myString[$i]<=9)
{
echo("$i is the first character that is a number.");
}
}
?>


Again, this is going off of C++ form, with a small amount of modifying. I am unsure as to whether this will work or not.

Also, if you only want it to print the first one, I think you would add a break; after the echo.

I hope this helps :thumbsup:

Cloudski
07-19-2002, 09:44 AM
Ok, well I tested my code, sand it doesn't work. Does anyone know how to get the integer value of a strings length? (EX: If $myString="abcd" the value would be 4....)

I know how to in C++, but not in PHP..

Jeewhizz
07-19-2002, 11:31 AM
OK, you use strlen() to find the string length....


<?
$int = strlen("abcd");
echo $int; //gives 4
?>


Jee

mordred
07-19-2002, 03:25 PM
Use the Power of Regular Expressions:


$numberFound = preg_match("/\d/", $myString, $arr);
$offset = strpos($myString, $arr[0]);
echo $offset;


BTW: Cloudski, I'm not all to sure that using the comparison operators on strings will always yield desired results because of PHPs inherent type juggling features. Also, you either have to use $myString{$i} to get at the character at that offset or to transform the string into an array via preg_split.

Cloudski
07-19-2002, 10:24 PM
Well, thanks for the information all... I only have experience in C++, so I don't know how PHP handles everything... yet.... *sigh* I still got a long way to go before I give back to this forum.

Thanks All for helping me help this person! :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum