Getting rid of the dollar sign? - php

Ok so i am importing a csv via a PHP script I am writing and the spreadsheet has values like $4090,00 and i need to insert these values in a mysql decimal field using PHP. Is there an easy way to get rid of the $ if its present in PHP

With str_replace, or even trim :
$str = str_replace('$', '', $str);
$str = trim($str, '$'); // only delete $ at start or end of the string
There are many solutions for this. Also, please note you have to use the period separator for decimals and integer part, not a comma.

$value = "$4090,00";
$value = preg_replace('/[\$,]/', '', $value);

Sure, you can use str_replace for this:
$nodollars = str_replace('$', '', $some_string);

Use sscanf if the input has a rigid format.

Related

PHP: remove last comma of a multipolygon

I have following issue:
I import WKT dynamicaly from DB into WKT Wicket Javascript library. I must do some substitutions to fit the WKT correctly. Since mysql fetches WKT AsText(SHAPE) i recive several arrays e.g. POLYGON((xxxx)),POLYGON((yyyy)) and so on.
First, I had to remove all "POLYGON" doing
$str = preg_replace('/^POLYGON/', '', $WKT[1]);
and add MULTIPOLYGON before <?php
tag in the wicket. It works.
Second, I must add comma between polygons, preicisely between "))((" brackets:
$str2 = str_replace(array('((', '))'), array('((', ')),'), $str);
It works but last comma remains what "slightly" deforms my multipolygon:
MULTIPOLYGON((xxx)),((yyy)),((zzz)),
How can I remove last comma?
I would be thankful for every regex or some other solution which can solve my problem.
In any string, you can remove the last X if you are sure that no X follows. So, you can use a negative lookahead: (,)(?!.*,), as seen here and replace it with empty string.
$result = preg_replace('/(,)(?!.*,)/', '', $str)
This doesn't look at the context though, it will just remove the last comma of any string, no matter where it is.
Thank you both - your answers were right and very helpful.
The problem was not string replacement. It was more the data fetching from DB.
Mysqli_fetch_array and mysqli_fetch_assoc return stringstringsring or arrayarrayarray for 3 rows fetched. That is why all commas were replaced.
I changed to mysqli_fetch_all ,then did minor replacements for each row (as array) and implode each one as variable. After i merged them into single variable, then I could apply your solutions. It is not sofisticated solution, but if it is packed into function it'll be fine.
($WKT = mysqli_fetch_all($result)) {
$str = preg_replace('/POLYGON/', '', $WKT[0]);
$str1 = preg_replace('/POLYGON/', '', $WKT[1]);
$str2 = preg_replace('/POLYGON/', '', $WKT[2]);
$str3 = implode($str);
$str4 = implode($str1);
$str5 = implode($str2);
$str6 = $str3 . $str4 . $str5;
$str7 = preg_replace('/\)\)/', ')),', $str6);
$str8 = rtrim($str7, ",");
echo $str8;
}

Remove characters from a variable

I have the following in a variable, |MyString|
I want to strip the leading | and the ending | returning MyString
What is the quickest and non intensive way of doing this?
Easiest way is probably
$result = trim($input, '|');
http://docs.php.net/trim
e.g.
<?php
$in = '|MyString|';
$result = trim($in, '|');
echo $result;
prints MyString
Checkout the str_replace function in PHP http://php.net/manual/en/function.str-replace.php
this should remove all '|' characters:
str_replace('|','',$myString)
You may be able to use a regular expression to only remove the first and last '|' or alternatively using the String trim() function may also work:
http://www.php.net/manual/en/function.trim.php
So, something like this:
$trimmedMyString = trim($myString, "|");
Worth trying anyway.

Use of PHP built-in ltrim() to remove a single character

Is there a simple way to use ltrim() to remove a single instance of a match instead of all matches?
I'm looping through array of strings and I'd like to remove the first, and only first, match (vowels in this case):
ltrim($value, "aeiouyAEIOUY");
With default behavior the string aardvark or Aardvark would be trimmed to be "rdvark". I'd like result to be "ardvark".
I'm not bound to ltrim by any means but it seemed the closest built-in PHP function. It would be nice of ltrim and rtrim had an optional parameter "limit", just saying... :)
Just use preg replace it has a limit option
eg
$value = preg_replace('/^[aeiouy]/i', '', $value, 1);
Regular expressions is probably overkill, but:
$value = preg_replace('/^[aeiouy]/i', '', $value);
Note the i makes it case-insensitive.
You can't use ltrim to do this for the reasons you say, nor can you use str_replace (which also has no limit). I think it's easiest just to use a regex:
$value = preg_replace('/^[aeiouy]/i', '', $value);
However if you really don't want to do that, you can use a substring, but you would have to check the position of any of those strings in the string in a loop as there is no php function that does such a check that I know of.
You can use the preg_replace function:
<?php
$value = preg_replace('/^[aeiouy]/i', '', $value);
?>
There are several way you can go about doing what you are looking to do.
Perhaps most straightforward would be a regular expression replacement like this:
$pattern = '/^[aeiouy]{1}/i';
$result = preg_replace($pattern, '', $original_string);
This is probably the most efficient way (so ignore my regular expressions answer):
if (strpos('aeiouyAEIOUY', $value[0]) !== false) $value = substr($value, 1);
Or,
if (stripos('aeiouy', $value[0]) !== false) $value = substr($value, 1);

PHP Remove Value of String with Variable Numbers

Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?
It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.
But in the meantime, you can use rtrim() to trim all numbers off of the right side.
$val = rtrim($val, '0123456789');
Examples
Input Output
nameofproject1001 nameofproject
nameofproject nameofproject
n4me0fproj3ct1001 n4me0fproj3ct
for string like, project12V123, It is better to do this
$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);
Will return:
Project12V
or use rtrim:
$text = rtrim($text,'0123456789');
You should definitely use regular expressions:
$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";
preg_replace('/[^a-z]/i', '', $string);

Filter out numbers in a string in php

assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
filter_var
flags for the filters
e.g. to get just numbers from the given string
<?php
$a = '!a-b.c3#j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
Edit:
1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].
You can use a regular expression to remove any character that is not a digit:
preg_replace('/\D/', '', $str)
Here the pattern \D describes any character that is not a digit (complement to \d).
Use PHP FILTER functions if you are using PHP 5.2.X, 5.3.x,5.4 . Its highly recommended
$mixed_input = "e3r4t5";
$only_numbers = filter_var($mixed_input, FILTER_SANITIZE_NUMBER_INT);
Please Go through with this link to know more
Replace everything that isn't a number and use that value.
$str = "foo1bar2baz3";
$num = intval(preg_replace("/[^0-9]/", "", $str));
You could use the following function:
function extract_numbers($string) {
preg_match_all('/([\d]+)/', $string, $match);
return $match;
}

Categories