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

Return spaces at start of string

Status
Not open for further replies.

ralphiooo

Programmer
Oct 23, 2005
64
GB
Hi, How do I strip the text part of a string leaving me just the spaces before the text

ie say I have

$string = "_____text" it would return "_____"
$string 2 = "__________text" would return "__________"

where _ = a space so you can see

Appreciate the help. Thanks
 
You could, I suppose, use a regular expression:

Code:
<?php
$string = '     text';

$string = preg_replace ('/^( +).*$/', '$1', $string);

print '<html><body><pre>';
print '"' . $string . '"';
print '</pre></body></html>';
?>

The above code will return the entire string, though, if there are no characters at the beginning of the string.



Want the best answers? Ask the best questions! TANSTAAFL!
 
this might be quicker than a regex.
function rtnspaces($string)
{
return substr($string,0,(strlen($string) - strlen(ltrim($string))));
}

 
Hi, sorry to be a pain but I did not explained my problem too clearly. I need to return all the spaces including the html entity &nbsp; to the left of the string. Appreciate if you could help once more. Cheers
 
at a guess - you could use sleipnir214's method as follows:
Code:
$string = '     text';
$string = html_entity_decode($string);
$string = preg_replace ('/^( +).*$/', '$1', $string);

print '<html><body><pre>';
print '"' . $string . '"';
print '</pre></body></html>';
?>

or mine

Code:
function rtnspaces($string)
{
    $string = html_entity_decode($string);
    return substr($string,0,(strlen($string) - strlen(ltrim($string))));
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top