Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Splitting Strings

Posted by gerry_w (gerry_w), 26 October 2005
Can anyone please help a PHP beginner with a problem.

I'm pulling a load of data from a MySQL database, including a 13 character sort key. I want to produce a link to a URL which is based on the sort key

e.g. Sort_Key = 0006001000100

would refer to document '01000100.pdf' in folder 00/060

So I need to split Sort_Key into three separate strings thus

00 . 060 . 01000100
in order to build the URL.

Hope all that makes sense, and thanks in advance for any advice.

Posted by admin (Graham Ellis), 26 October 2005
Hi, Gerry ... welcome.

I think unpack will do the trick ... here's an example ...

Code:
$dd = unpack("A2Icecream/A2Cream/A4Custard","00112233");
print ($dd[Icecream]."\n");
print ($dd[Cream]."\n");
print ($dd[Custard]."\n");


That's 2 characters into the element called Icecream, 2 characters into the element called Cream, and 4 into the element called custard.  

The output is

Code:
00
11
2233


Posted by gerry_w (gerry_w), 27 October 2005
Thanks for that Graham. I ended up trawling the manual before I read your reply and I used the substr function instead, which seemed to do the job equally well.

http://uk2.php.net/substr

From memory (the code's at work) my code was something like this (excuse any duff syntax)

Code:
<?
$sort_key = "0006001000100" // value extracted from mysql db

$start = substr($sort_key, 0, 2); // returns '00'
$middle = substr($sort_key, 2, 3); // returns '060'
$end = substr($sort_key, 4, 8); // returns '01000100'

$url = "$start/$middle/$end.pdf"; //returns 00/060/01000100.pdf

print ("<a href='$url'>CLICK HERE</a>");



Thanks again for taking the time to respond. I just had a quick trawl through the forum and there's loads here I can put to use  



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho