Re: Finding the Middle elements of a String

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Please don't do this, it *will* break on multibyte strings, as those "arrays" are not based on characters but bytes.

On 11 May 2014 20:01:28 BST, Jigar Dhulla <jigar.tidus@xxxxxxxxx> wrote:
>Hi,
>
>As long as I know you can consider a string as array in php. Means
>$string[0] is "a", $string[1] is "p" and so on. So you can use a
>foreach
>like :
>
>foreach($string as $k => $v){
>    if($v == ",") $pos[] = $k;
>}
>
>$pos will be an array with values of commas position.
>
>Note: index starts with 0. So $pos[0] will be 5 and so on.
>
>Please correct me if I am wrong. I have not tested this or used this
>method
>anywhere.
>On 11-May-2014 11:32 pm, "dealTek" <dealtek@xxxxxxxxx> wrote:
>
>> Hi all,
>>
>> Let's say the string is "apple,cherry,peach,pear" (not an array just
>a
>> text string)
>>
>> I see that I can use these (strpos & strripos) to search for the
>first or
>> last "," - but how to I search for the ones in the middle (like third
>comma
>> or 4th comma)?
>>
>> strpos — Find the position of the first occurrence of a substring in
>a
>> string
>>
>> strripos — Find the position of the last occurrence of a
>case-insensitive
>> substring in a string
>>
>> Thanks in advance
>>
>> ex:
>>
>> $this1 = "apple,cherry,peach,pear";
>> $findme   = ',';
>> $pos = strpos($this1, $findme);
>> $pos2 = strripos($this1, $findme);
>>
>>
>> $showfirst = substr($this1, 0, $pos);
>> $showlast = substr($this1, $pos2+1, 9999 );
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> --
>> Thanks,
>> Dave - DealTek
>> dealtek@xxxxxxxxx
>> [db-14]
>>
>>
>> --
>> PHP General Mailing List (http://www.php.net/)
>> To unsubscribe, visit: http://www.php.net/unsub.php
>>
>>

Thanks,
Ash

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux