how to get left portion of string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • voam
    New Member
    • Nov 2006
    • 1

    how to get left portion of string?

    Hi,

    I come from a VB background and often to prepare a string for insertion into a database I would make sure that the length of the string did not exceed the size of varchar that the database could handle. So for example, assuming the database could only handle names up to 50 characters in length, I would write
    Code:
    Name = Left(Name,50)
    and then go ahead and insert the string without fear of any data being truncated.
    How do I go about this in PHP? I see the strlen() function but I don't see a way to get the first x characters of a string. Am I missing something?

    Thanks in advance as I am very new to PHP.
  • Velhari
    New Member
    • Sep 2006
    • 46

    #2
    Originally posted by voam
    Hi,

    I come from a VB background and often to prepare a string for insertion into a database I would make sure that the length of the string did not exceed the size of varchar that the database could handle. So for example, assuming the database could only handle names up to 50 characters in length, I would write
    Code:
    Name = Left(Name,50)
    and then go ahead and insert the string without fear of any data being truncated.
    How do I go about this in PHP? I see the strlen() function but I don't see a way to get the first x characters of a string. Am I missing something?

    Thanks in advance as I am very new to PHP.

    Hi,
    Yeah! as a developer we didnt have to worry about no such method is not there in PhP..... We will have to simulate that kind of method in our scripting too.........
    The following code will suitable for you...........

    [PHP]<?
    echo Left("SomeText" ,5);

    function Left($str,$len)
    {
    $length=strlen( $str);
    if ( $len > $length ) $len=$length;
    else if ( $len <= 0 ) $new = $str;
    else
    {
    for ( $i=0; $i<$len; $i++ )
    {
    $temp[]=$str{$i};
    }
    $new = implode ("",$temp);
    }
    return ($new);
    }
    ?>[/PHP]

    I think This code will fulfill your query.

    With Regards,
    Velmurugan.H

    Comment

    • ronverdonk
      Recognized Expert Specialist
      • Jul 2006
      • 4259

      #3
      What is all this code about?
      There is a simple PHP function for that, it is called SUBSTR(). In your case you would code[php]$new_string = substr($old_str ing, 0, 50);[/php]
      If the old string is shorter then 50, it will take the original's length to copy.

      Ronald :cool:

      Comment

      Working...