As part of a form I collect a users bank details which includes their sort code. The sort code is stored in the database as six numbers, for example 771731.
I'd prefer to store the sort code in this format (without the hyphens) as it makes it easier for me to work with in other areas of the site. I want to output the sort code in one area of the site but in the format 77-17-31 using PHP.
I have searched Google for a solution but surprisingly found very little.
This is the prefect use-case for wordwrap(), just use it like this:
$code = "771731";
echo wordwrap($code, 2, "-", TRUE);
output:
77-17-31
Just figured this out using PHP functions, thought I'd post the answer in case it helped anyone else doing a Google search...
function formatSortCode($str) {
return implode("-", str_split($str, 2));
}
echo formatSortCode('771731'); // outputs 77-17-31
I arrived here looking for a JavaScript answer not realising it was a PHP question. Tweaking #MichaelLB's answer, the JavaScript translation is
function formatSortCode(str) {
return (String(str).match(/.{1,2}/g) || []).join('-');
}
formatSortCode(123456789);
>>> "12-34-56-78-9"
Related
This is my first question on this site, sorry if it is not clear enough.
So my problem is that, i would like to get all of the product IDs from a webshop, that has no API.
A product id looks like: xy-000000
I know that I need a webscraper, but the problem is that i don’t know how to find a specific word like xy- 000000 with it. I tried many web-scrapers, but the only thing that i could find with them is html tags like the title or keywords.
I searched a lot for it on google, and found some web scrapers, bat they are not working fine for me.
As i mentioned, i would like to get all of the product IDs from a different webshop using php, for finding some products that i am not selling. (My webshop has the same product IDs as the other.)
Can anyone please help me find a php script that is similar to what i need?
So this is the code that i am trying to use:
<?php
$data = file_get_contents('https://www.mesemix.hu/hu/superman-ruhanemuk/11292-szuperhosoek-mintas-zokni.html');
error_reporting(0);
preg_match('/<title>([^<]+)<\/title>/i', $data, $matches);
$title = $matches[1];
preg_match('/[0-9]{6}/', $data, $matches);
$number = $matches[1];
preg_match('/<img[^>]*src=[\'"]([^\'"]+)[\'"][^>]*>/i', $data, $matches);
$img = $matches[1];
echo $title."<br>\n";
echo $img."<br>\n";
echo $number;
echo $data;
?>
The problem is that i can not find the 6 digit number with it. ($number)
In the webshop's source code it looks like this:
var productReference = 'SP- 418070';
If there is anything wrong with my question please let me know.
The Term you are looking for is "Web-Scraper"
You can do it in a couple of different ways.
One of these 2 PHP libraries
http://simplehtmldom.sourceforge.net/
Or
https://github.com/FriendsOfPHP/Goutte
Both are very simple to use there are documentations for both of them
The way they work are just like jQuery (javascript) you target the data that you need to get by the CSS selectors
I'm trying to pull each of the viewer names from a JSON file in PHP.
I've looked around the Internet extensively for a working example that will offer me the result I desire without much success.
I'm really struggling to find an example that fits my needs on the Internet to help me with what is likely a very simple thing to accomplish.
I've got a JSON file that spits out several values on the Internet and I'm looking to extract every single line from one particular section.
Seeing a working example will likely help me understand what I am doing.
The JSON file that I am using for example is:
https://tmi.twitch.tv/group/user/dansgaming/chatters
I am trying to extract each single line from the "viewers" section in this file.
I've captured the data using the following PHP:
$testviewers = json_decode(#file_get_contents('https://tmi.twitch.tv/group/user/' . $streamName . '/chatters'), true);
var_dump($testviewers['chatters']['viewers']);
It turns out this isn't having the desired result for me.
I simply want each line in the viewer's section to be echoed out with page breaks.
What am I doing wrong? I've tried about two hundred different approaches to this one and have to admit this is my first real time working with JSON.
I've tried to search the Internet for answers and found many tutorials but none have made any sense to me and I know that seeing how to accomplish the result will help me learn exactly what should be going on.
In an ideal world, it will simply output each "viewer" on a separate line that I can work with. If I could echo each of them and then concatenate with a page break or the word "viewer:" before each one this would be a huge help and I'll be able to take it further and likely learn a great deal in the process.
this my way echo from json
$json = json_decode($response, true);
foreach($json['chatters'] as $key => $value)
{
if(!empty($value['viewers']))
{
$VIEWER = $value['viewers'];
$VIEWER = addslashes($VIEWER );
$VIEWER = trim(preg_replace('/\s\s+/', ' ', $VIEWER ));
}
else
{
$VIEWER = '';
}
echo 'VIEWER = '.$VIEWER .'</br>';
}
just make sure the foreach is true, maybe can help.
Turns out the issue here was a PHP error that wasn't displaying. The code was timing out because of how large the JSON file was and a low limit on my machine.
I think this is what you want....
$array = json_decode($your_json,true);
foreach($array['chatters']['viewers'] as $r) echo $r.'<br>';
hello im a newbie in php i am trying make a search function using php but only inside the website without any database
basically if i want to search a string namely "Health" it would display the lines
The Joys of Health
Healthy Diets
This snippet is the only thing i could find if properly coded would output the "lines" i want
$myPage = array("directory.php","pages.php");
$lines = file($myPage[n]);
echo $lines[n];
i havent tried it yet if it would work but before i do i want to ask if there is any better way to do this?
if my files have too many lines wont it stress out the server?
The file() function will return an array. You should use file_get_contents() instead, as it returns a string.
Then, use regular expressions to find specific text within a link.
Your goal is fine but the method you're thinking about is not. the file() function read a file, line by line, and inserts it into an array. This assumes the HTML is well-structured in a human-readable fashion, which is not always the case. However, if you're the one providing the HTML and you make sure the structure is perfectly defined, ok... here you have the example you provided us with but complete (take into account it's the 'wrong' way of solving your problem, but if you want to follow that pattern, it's ok):
function pagesearch($pages, $string) {
if (!empty($pages) && !empty($string)) {
$tags = [];
foreach ($pages as $page) {
if ($lines = file($page)) {
foreach ($lines as $line) {
if (!empty($line)) {
if (mb_strpos($line, $string)) {
$tags[$page][] = $line;
}
}
}
}
}
return $tags;
}
}
This will return you an array with all the pages you referenced with all occurrences of the word you look for, separated by page. As I said, it's not the way you want to solve this, but it's a way.
Hope that helps
Because you do not want to use any database and because the term database is very broad and includes the file-system you want to do a search in some database without having a database.
That makes no sense. In your case one database at least is the file-system. If you can accept the fact that you want to search a database (here your html files) but you do not want to use a database to store anything related to the search (e.g. some index or cached results), then what you suggest is basically how it is working: A real-time, text-based, line-by-line file-search.
Sure it is very rudimentary but as your constraint is "no database", you have already found the only possible way. And yes it will stress your server when used because real-time search is expensive.
Otherwise normally Lucene/Solr is used for the job but that is a database and a server even.
I'm trying to add a feature to generate a difference report between 2 20,000 character sections of text. I've done some Googling and I heard about Pear's diff library - which has been discontinued - and found this: https://github.com/paulgb/simplediff/blob/5bfe1d2a8f967c7901ace50f04ac2d9308ed3169/simplediff.php
Ideally I'd like to see what was removed, edited, or added and be able to show that to the user. Are there any libraries or simple ways of accomplishing this that you may know of?
I use this code in a live project
http://svn.geograph.org.uk/svn/branches/british-isles/libs/3rdparty/simplediff.inc.php
Example use
http://svn.geograph.org.uk/svn/branches/british-isles/public_html/article/diff.php
but the code is very simple
$a1 = explode("\n",$file1);
$a2 = explode("\n",$file2);
print diff2table($a1,$a2);
(the code just accepts the input as arrays, and outputs html table. But diff2table can be customised)
I'd like to make a script where the user can enter a sum e.g. 4^5+(56+2)/3 or any other basic maths sum (no functions etc.) how would I go about doing this? Presumably regex. Could somebody point me in the right direction - I'm guessing this isn't going to be too easy so I'd just like some advice on where to start and I'll take it from there.
Have a look at this: http://www.webcheatsheet.com/php/regular_expressions.php
It's a good intro to Regular Expressions and how to use them in PHP.
Yes, someone can (and probably will) just give you the regex you need to work this out but it helps a lot if you understand HOW your regex works. They look scary but aren't that bad really...
this is not my code, but there is a great PHP snippet that lets you use Google Calculator to do the calculations. So you can just enter your query (ie, "7+3") using regular/FOIL notation or whatever, and it will return the result.
http://www.hawkee.com/snippet/5812/
<?php
// Google calculator
function do_calculator($query){
if (!empty($query)){
$url = "http://www.google.co.uk/search?q=".urlencode($query);
$f = array("Â", "<font size=-2> </font>", " × 10", "<sup>", "</sup>");$t = array("", "", "e", "^", "");
preg_match('/<h2 class=r style="font-size:138%"><b>(.*?)<\/b><\/h2>/', file_get_contents($url), $matches);
if (!$matches['1']){
return 'Your input could not be processed..';
} else {
return str_replace($f, $t, $matches['1']);
}
} else {
return 'You must supply a query.';
}
}
?>
The easy way to do it is with eval(). If you're accepting arbitrary input from a web form and executing in on a server, though, you MUST be careful to only accept valid expressions. Use a regex for that.