I am currently using the following function to grab the product code number for a filename such as "62017 THOR.jpg"
$number = (int) $value;
Leaving me with 62017
The trouble is some of these files have prefixes which need to be left in place ie "WST 62017.jpg"
So im after
WST 62017
not
62017
Could someone help me, either redo what im using or alter ?
replace all characters except the numbers from the image name and get only numbers.
$number = preg_replace("~[^0-9]~", "", $value);
If you want to capture everything before the number and the number as well, you can use:
$value = "WST 62017.jpg";
$number = preg_replace('/^(.*?\d*)\..*/',"$1",trim($value));
// $number is "WST 62017"
See it
You could do it like this:
$value = preg_replace('/^(.*\d+).*$/', '\1', $filename);
It should replace everything after the first numeric value with nothing, leaving everything in front of it in place. Note that you wont't be able to cast the number to int, then.
Related
I have a string: /userPosts/hemlata993/20
I want to remove this /userPosts/hemlata993/.
I checked some answers but not being able to remove the first part. How can I do that? I am using php.
$string = /userPosts/hemlata993/20
I want the output as 20 because 20 is the directory or file name that I want to get
You can do it as follows:
$p = basename(parse_url("/userPosts/hemlata993/20")['path']);
echo $p; //20
If this is what you want and the format of the string is always going to be like the one that you provided, this will work:
$string = "/userPosts/hemlata993/20";
$string_arr = (explode("/",$string));
echo $string_arr[3];
sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);
My questions is somewhat based off this:
How can I get the last 7 characters of a PHP string?
Mine is similar. I need to get the last x characters of a string and to stop when I reach "-"
for example, I have a booking code:
N-903
and I can get the last 3 characters like so:
$booking_Code = N-903
$booking_Code = substr($booking_Code, -3);
and the result will be:
903
This number however will increase, so I expect to see booking codes like:
N-1001
N-22520
N-201548
so the code:
substr($booking_Code, -3);
would become useless. Is there any way to use "-" as a delimiter? I think that's the correct term to use. because the number that's generated will always come after the hyphen "-". Any help would be greatly appreciated
try this
<?php
$tmpArray = explode("-",$mystr);
echo $tmpArray[1];
?>
You might want to refer to explode function in php.
As an alternative, you could also use strrchr in conjunction with the substr you have:
$booking_Code = 'N-903';
$booking_Code = substr(strrchr($booking_Code, '-'), 1);
echo $booking_Code; // 903
this is my first question here at Stackoverflow so please bear with me :)
What I have been trying to do for the last couple of hours is replacing symbols on upload and download from the database.
How it should be:
Input: 100.000,25
Stored in database: 100000.25
Output: 100.200,25
The reason hereof is that i need the comma as decimal separator, and dot as thousand separators. I need to still be able to add/multiply and more with the numbers stored in the database.
What works the best of what I have tried so far:
// Value from form input:
$value = 100.200,25;
// Removing all but numbers and comma
$remove_symbols = array("+"," ",".","-","'","\"","&","!","?",":",";","#","~","=","/","$","£","^","(",")","_","<",">");
$db_value = str_replace($remove_symbols, '', $value);
// $db_value insert into db
// Pulling out the data
$db_pulled = number_format($row['liter'],2,',','.');
echo $db_pulled;
:( returns: 100.200,00 (should return 100.200,25)
Your questions are a bit confusing and you don't tag them well. For example a php tag would be more appropriate and sufficient. (I've modified it for you now)
OK. The problem you are having is because you need to replace comma with a dot because that's how float values are represented. In your example it probably gets truncated when you insert it in the DB.
here is what you can do:
<?php
$numString = "100.200,25";
$numString = str_replace(array('.', ','), array('','.'), $numString);
$num = floatval($numString);
echo $num;
?>
Seeing that your code returns: 100.200,00 (should return 100.200,25)
Your databases table field seems to be in Int format instead of Decimal format.
For more information about Numeric field types visit http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
My new phone does not recognize a phone number unless its area code matches the incoming call. Since I live in Idaho where an area code is not needed for in-state calls, many of my contacts were saved without an area code. Since I have thousands of contacts stored in my phone, it would not be practical to manually update them. I decided to write the following PHP script to handle the problem. It seems to work well, except that I'm finding duplicate area codes at the beginning of random contacts.
<?php
//the script can take a while to complete
set_time_limit(200);
function validate_area_code($number) {
//digits are taken one by one out of $number, and insert in to $numString
$numString = "";
for ($i = 0; $i < strlen($number); $i++) {
$curr = substr($number,$i,1);
//only copy from $number to $numString when the character is numeric
if (is_numeric($curr)) {
$numString = $numString . $curr;
}
}
//add area code "208" to the beginning of any phone number of length 7
if (strlen($numString) == 7) {
return "208" . $numString;
//remove country code (none of the contacts are outside the U.S.)
} else if (strlen($numString) == 11) {
return preg_replace("/^1/","",$numString);
} else {
return $numString;
}
}
//matches any phone number in the csv
$pattern = "/((1? ?\(?[2-9]\d\d\)? *)? ?\d\d\d-?\d\d\d\d)/";
$csv = file_get_contents("contacts2.CSV");
preg_match_all($pattern,$csv,$matches);
foreach ($matches[0] as $key1 => $value) {
/*create a pattern that matches the specific phone number by adding slashes before possible special characters*/
$pattern = preg_replace("/\(|\)|\-/","\\\\$0",$value);
//create the replacement phone number
$replacement = validate_area_code($value);
//add delimeters
$pattern = "/" . $pattern . "/";
$csv = preg_replace($pattern,$replacement,$csv);
}
echo $csv;
?>
Is there a better approach to modifying the CSV? Also, is there a way to minimize the number of passes over the CSV? In the script above, preg_replace is called thousands of times on a very large String.
If I understand you correctly, you just need to prepend the area code to any 7-digit phone number anywhere in this file, right? I have no idea what kind of system you're on, but if you have some decent tools, here are a couple options. And of course, the approaches they take can presumably be implemented in PHP; that's just not one of my languages.
So, how about a sed one-liner? Just look for 7-digit phone numbers, bounded by either beginning of line or comma on the left, and comma or end of line on the right.
sed -r 's/(^|,)([0-9]{3}-[0-9]{4})(,|$)/\1208-\2\3/g' contacts.csv
Or if you want to only apply it to certain fields, perl (or awk) would be easier. Suppose it's the second field:
perl -F, -ane '$"=","; $F[1]=~s/^[0-9]{3}-[0-9]{4}$/208-$&/; print "#F";' contacts.csv
The -F, indicates the field separator, the $" is the output field separator (yes, it gets assigned once per loop, oh well), the arrays are zero-indexed so second field is $F[1], there's a run-of-the-mill substitution, and you print the results.
Ah programs... sometimes a 10-min hack is better.
If it were me... I'd import the CSV into Excel, sort it by something - maybe the length of the phone number or something. Make a new col for the fixed phone number. When you have a group of similarly-fouled numbers, make a formula to fix. Same for the next group. Should be pretty quick, no? Then export to .csv again, omitting the bad col.
A little more digging on my own revealed the issues with the regex in my question. The problem is with duplicate contacts in the csv.
Example:
(208) 555-5555, 555-5555
After the first pass becomes:
2085555555, 208555555
and After the second pass becomes
2082085555555, 2082085555555
I worked around this by changing the replacement regex to:
//add escapes for special characters
$pattern = preg_replace("/\(|\)|\-|\./","\\\\$0",$value);
//add delimiters, and optional area code
$pattern = "/(\(?[0-9]{3}\)?)? ?" . $pattern . "/";