How exactly do I check of the first character in $value
is £ and then remove it if is?
Even better would be to check if it is not a number and then remove it.
My current code:
echo '<dl style="margin-bottom: 1em;">';
foreach ($row as $key => $value)
{
echo "<dt>$key</dt><dd>$value</dd>";
}
echo '</dl>';
You know there's a function for that? http://php.net/manual/en/function.str-replace.php
str_replace('£', '', $value);
or of course
ltrim($value, '£')
if you only want to get rid of the first character
$value = preg_replace('/^\\D*/', '', $value);
This will remove all the non-digits from the beginning of $value
You can do this:
if (substr($value,0,1)=="£") $value = substr($value,1);
or
if ($value[0]=="£") $value = substr($value,1);
or (this way you check if the character (substracted from value) is numeric or not)..
if (!is_numeric(substr($value,0,1))) $value = substr($value,1);
if ($values[0] == '£') { then
$values = substr($values, 1); // grab char 1 onwards, removing char 0/£
}
This uses the "treat string as an array" shortcut notation, and boils down to
if (substr($values, 0, 1) == '£') {
Note that this will fail on multi-byte character sets, and you'd have to use mb_substr()
instead, which is the multibyte-aware version.
You can subtract the first character and perform a is_int() check on that, like so:
$firstChar = substr($yourString, 0, 1);
if(!is_int($firstChar)) {
// Not an integer, strip the first character altogether
$newString = substr($yourString, 1);
}
Then, $newString will hold the content, without the first character (if that was not an integer).
You can use trim()
$value = trim($value, "£");
In your code you can do:
foreach($row as $key => $value){
echo "<dt>$key</dt><dd>".trim($value, "£")."</dd>" ;
}
Some folks are suggesting trim - which is probably fine for most uses, but might also remove a trailing '£' as well.
If you really only want to remove a '£' from the start of the string, you might want to look at using ltrim
e.g.
$value = ltrim($value, '£');
(I'm aware the intent of the question is about stripping non-numerics from a string, but I found this while Googling for removing a character only from the start, so no doubt others will as well. This should help them out)
This might be useful for future visitors.
The question is removing the first character if it is a "£".
Of course this could be any character so the issue with the suggest ltrim
is that it will remove all of the consecutive characters, not just the first, e.g.
ltrim('££10', '£');
Would output 10
not £10
. In this case, this might be acceptable but not for every case as we only want the first character.
preg_replace('/^'.$char.'/', '', $input);
Will do this. $char
is the character that you want to check (in this case, '£').
The regex, /^£/
, would look for exactly one instance of £ anchored to the start of the string.