Basic php string operations
Example
<?php
$url = '
http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
output:
Array
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
/path
Question:
For example, I want to do something with the host, like run
some string replace operations on it, but how do I access
it?
.oO(ttdevelop)
>Example
> <?php
> $url = '
http://username:password@hostname/path?arg=value#anchor';
>
> print_r(parse_url($url));
>
> echo parse_url($url, PHP_URL_PATH);
> ?>
>
> output:
>
> Array
> (
> [scheme] => http
> [host] => hostname
> [user] => username
> [pass] => password
> [path] => /path
> [query] => arg=value
> [fragment] => anchor
> )
> /path
>
> Question:
> For example, I want to do something with the host, like
run some string
>replace operations on it, but how do I access it?
You should read about how to use variables and arrays or use
the second
parameter of parse_url() to only return the host name as a
string like
you did in the second example (see the manual for details).
Then assign
the return value to a variable and you can do whatever you
want with it.
Variables
http://www.php.net/manual/en/language.variables.php
Arrays
http://www.php.net/manual/en/language.types.array.php
parse_url
http://www.php.net/manual/en/function.parse-url.php
Micha
Similar Messages
-
String operations on internal table text....
Original table is consists of 2 columns:
E
RFC error(SM_DHTCLNT010_READ): Error when opening connection
E RFC error(SM_DHLCLNT010_READ): Error when opening connection
E RFC error(SM_DHKCLNT010_READ): Error when opening connection
E RFC error(SM_E10CLNT000_READ): 'tdhtci00.emea.gdc:sapgw02' E No read RFC FOR SM_B72CLNT003_READ
E No read RFC FOR SM_B71CLNT003_READ
S Clients for system 'E21' found in RFC 'SM_E21CLNT001_READ'
S Clients for system 'E22' found in RFC 'SM_E22CLNT001_READ'
S Clients for system 'E23' found in RFC 'SM_E22CLNT001_READ'
Now we need to apply string operations such that result table is 3 columns with new refined message:
status sid
Message NEW_TEXT
E DHT
RFC error Error when opening connectionE DHL RFC error Error when opening connection
E DHK RFC error Error when opening connection
E E10 RFC error tdhtci00.emea.gdc:sapgw02
E B72 No RFC LINK
E B71 No RFC LINK
S E21 DATA READ
S E22 DATA READ
S E23 DATA READ
String conditions to arrive at new table is:
1) to get SID column : the conditions are
If the Status is RFC Error then next 3 Characters after the _ must be extracted as SID
Else the SID is between the first and the second inverted comma
Example: Clients for system 'E21' found in RFC 'SM_E21CLNT001_READ'extracts E21 as SID
2) for message column
· message RFC Error if the message text
starts with RFC Error
· message no RFC Link if the message text starts with No read RFC*
· message Data Read if the Substring found in RFC</b> was found in the Message
3) If the Status is RFC Error then the whole Textstring behind the : must be Extracted
For example if message is RFC error(SM_DHLCLNT010_READ): Error when opening connection NEW_TEXT will be Error when opening connection
Need ur inputs on these.
Bset regards,
SubbaHi,
this u can acheive simply using offset:
var_name+off(len). "
e.g. wa_message-fld+0(3) = first threee characters
wa_message-fld(3) same as above first three characters
wa_message-fld+2(2) " will display second and third characte of wa_message-fld
this u can use to set condtions like :
if wa_message-fld(9) = 'RFC Error'.
"process here
endif.
Hope this will help u...
Jogdand M B -
Need help making basic php gallery.
Hi guys,
Thanks for checking out my post...
I want to create a gallery, using php, for a client site
similar to the one at
http://www.danwheldon.com/gallery.cfm
where you click on a thumbnail and it refreshes the page with the
larger image within the websites' layout and above the rest of the
thumbnails.
At the moment, my site has a template layout called main.php
and I'm using a basic php query to bring up gallery.php
(main.php?pagename=gallery) so the thumbnails are displayed in the
template.
How can I add another query to the links so that when you
click on one of the thumbnails, it refreshes
main.php?pagename=gallery with the enlarged image above the rest of
the thumbnails?
Thank you very much and I hope to hear from you.
All the best,
MarkSpindrift wrote:
> How can I add another query to the links so that when
you click on one of the
> thumbnails, it refreshes main.php?pagename=gallery with
the enlarged image
> above the rest of the thumbnails?
Seb posted this the other day. I think it fits in with what
you want and
can be adapted.
Someone asked. How are pages created like this:
http://www.foo.com/fooing.php?id=10
http://www.foo.com/fooing.php?id=20
ANSWER:
whatever is after the "?" is a variable ("id") and its value
("20").
The variable value is retreived by PHP via the $_GET array:
<?php
$var = $_GET['id'];
echo $var;
?>
This will output the variable value (10 or 20).
Then you can use these values to outuput different things:
<?php
$var = $_GET['id'];
if ($var == 10){
do_something();
if ($var == 20){
do_someting_else();
?>
A typical example would be with an image gallery, each
thumbnail would
have a link to the same page, but with a different variable:
<a href="big_image.php?id=10"><img
src="thumb10.jpg"></a>
so each thumbnail would open the same page, but in this page,
the
approperiate bigger image would be outputted buy PHP
according to the
variable:
<?php
$big_image = $_GET['id'].'.jpg';
echo '<img src="'.$big_image.'">';
?>
this will output:
<img src="10.jpg"> -
Learning the basics of EXISTS operator
I am learning the basics of EXISTS operator.
create table loans
(acc_id number,
balance number(10,2));
insert into loans
(acc_id, balance)
values
(100, 20000);
insert into loans
(acc_id, balance)
values
(110, 22000);
insert into loans
(acc_id, balance)
values
(120, 7000);
insert into loans
(acc_id, balance)
values
(130, 172.99);
SQL> select * from loans;
ACC_ID BALANCE
100 20000
110 22000
120 7000
130 172.99
create table defaulters
(cust_id number,
name varchar2(20),
acc_id number);
insert into defaulters
(cust_id, name, acc_id)
values
(1,'Vajaal',110);
insert into defaulters
(cust_id, name, acc_id)
values
(2,'Mostert',130);
SQL> select * from defaulters;
CUST_ID NAME ACC_ID
1 Vajaal 110
2 Mostert 130
SQL> select acc_id from loans
2 where exists(select 1 from defaulters
3 where loans.acc_id=defaulters.acc_id);
ACC_ID
110
130It just returns all acc_id rows in Loans table which has corresponding ACC_IDs present in defaulters.
On 10gR2 SQL Reference, for EXISTS operator, it says ' An EXISTS condition tests for existence of rows in a subquery' .
Would it be wrong if i say, EXISTS operator can be used when you want to return all rows in the Outerquery which has matching records in the Innerquery.Would it be wrong if i say, EXISTS operator
can be used when you want to return all rows in the
Outerquery which has matching records in the
Innerquery.Depends on what you understand with "matching".
See following examples:
In this case matching means "<>" i.e. return all loans who have at least one row that differs in defaulters table (of course it returns all loans, because defaulters has 2 rows with different acc_id, BTW look also for NULLs and comparisons involving NULLs)
SQL> ed
Wrote file afiedt.buf
1 select acc_id from loans
2 where exists(
3 select 1 from defaulters
4* where loans.acc_id<>defaulters.acc_id)
SQL> /
ACC_ID
100
110
120
130See also following query:
SQL> ed
Wrote file afiedt.buf
1 select acc_id from loans
2 where exists(
3 select 1 from defaulters
4* )
SQL> /
ACC_ID
100
110
120
130There isn't any condition at all, so any row in defaulters is "matching" row in this case.
So I'd stick with explanation in documentation this time ;)
Gints Plivna
http://www.gplivna.eu -
String operations in internal table
Dear friends..
Good morning.
I wish to know.. how i segregate the field from a database table to internal table into two different internal table field. say for example.
i have db table tab1 which has field number
tab1 -> number
and i have another internal table itab1 whic has two fields numa and numb
tab1 -> numa
-> numb
i have value in tab1->number is 001 and 0001
i wish to segregate this two values in to internal table
if the value is 001 then it should be into 001 -> numa
if the value is 0001 then it should be into 0001-> numb
i dont know how to perform the string operations in internal table.. would you like to tell me how i fix this problem any suggetion, article, code will be great help of mine..
thanking you
Regards
NaimHi,
what u can do is check the lenth
lit_data_tab.
lit_data_3
lit_data_4.
lv_char3 type char3.
lv_char4 type char4.
lv_length type i.
loop at lit_data_tab.
lv_length = STRLEN ( lit_data_tab-value ).
if lv_length = 3.
lv_char3 = lit_data_tab-value .
append lv_char3 to lv_char3 type char3.
else.
lv_char4 = lit_data_tab-value .
append lv_char4 to lv_char3 type char4.
endif.
endloop.
if u want
numa numb
003 0003.
then u have to loop in one table and modify other.
that is any one table should contains both the field.
read the table with one field
mark helpfull answers
Regards
Message was edited by: Manoj Gupta -
Efficiency of Java String operations
Hi,
for an Information Retrieval project, I need to make extensive use of String operations on a vast number of documents, and in particular involving lots of substring() operations.
I'd like to get a feeling how efficient the substring() method of java.lang.String is implemented just to understand whether trying to optimize it would be a reasonable option (I was thinking of an algorithm for efficient string pattern matching such as the Knuth-Morris-Pratt algorithm, but if java.lang.String already applies similarly efficient algorithms I would not bother).
Can someone help?
JThanks for your comment. Yes of course you're right, I
mean indexOf(). If so (thanks DrClap), let me enter the discussion.
The indexOf() implements a so called "brute force algorithm".
The performance is O(n*m), where n is the length of the text, and
m is the length of the pattern, but is close to n on the average.
The KMP is O(n), so the performance gain should be hardly noticeable.
To get a real performance gain you should look at the BM (Boyer-Moore,
O(n/m)) algorithm or some of its descendants.
As for java.util.regex package, as far as i understand it should be
several times slower than indexOf(), because it reads EACH character through an interface method (as opposed to direct array access in indexOf()).
Though it's still to be proved experimentally. -
To use Character string operator in ABAP
HI,
I have a problem with joining the two fields with different data length i.e
OBJKY has length (30).
tknum has length (10).
the above read table i_nast works as long as both has the records not greater than 10 and I do have some records with greater than 10 for OBJKY in the database and my read is failing at that scenario, I need to use a charater string operator, as I am new to ABAP, can any one suggest me how to do .
...SQL..
select OBJKY DATVR from nast
into corresponding fields of table i_nast
where KSCHL = 'ZBOL'.
sort i_nast by OBJKY.
LOOP at i_ship_data.
read table i_nast with key
OBJKY = i_ship_data-tknum binary search.
if sy-subrc = 0.
move: i_nast-datvr to i_ship_data-datvr.
endif.
modift i_ship_data.
ENDLOOP.HI,
Since OBJKY and TKNUM are with different lengths the Read statement works only
when OBJKY has a 10 character value identical to TKNUM.
but if we can assume that only first 10 characters of OBJKY are to be comapred with TKNUM then we can try the under mentioned approach:
Create a new field in the Internal table I_NAST with length 10 characters.(I_NAST-OBJKY_TEMP).
now assign the first 10 characters of OBJKY to this new field :
LOOP AT I_NAST.
MOVE I_INAST-OBJKY+0(10) TO OBJKY_TEMP.
MODIFY I_NAST.
ENDLOOP.
Now you can Modify your READ STATEMENT :
LOOP at i_ship_data.
read table i_nast with key
OBJKY_TEMP = i_ship_data-tknum binary search.
if sy-subrc = 0.
move: i_nast-datvr to i_ship_data-datvr.
endif.
modift i_ship_data.
ENDLOOP.
Hope this will help.
Note: You can pick up any 10 characters starting from 1 to 20 th character of the field
I_INAST-OBJKY.
Reward Points if found helpfull..
Cheers,
Chandra Sekhar. -
Perl versus other "scripting" languages when doing string operations
I've been told that perl is a "scripting" language like the other languages mentioned in this forum.
If that's true, can these other languages handle the following spec as well as perl can? (See spec at end of this post.)
Or is perl stronger in string operations than the other scripting languages mentioned here?
Here's the spec:
1. I give your program a twenty-letter alphabet (any twenty letter alphabet)
For example:
ABCDEFGHIJKLMNOPQRST
2. I also give your program four groups (any four groups) of letters in this alphabet:
For example:
s: A,B,C,D,E
p: F,G,H,I,J
d: K,L,M,N,O
e: P,Q,R,S,T
3. I also give your program a sequence over the twenty-letter alphabet that I gave you in Step (1) above:
For example:
ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA
4. Given this sequence,you search for pairs of adjacent letters (x,y) where X and y are from different groups (the groups defined in Step (2) above.)
Also, you return the results of this search by giving me back the following two strings:
ABCD(EF)GHI(JK)LMN(OP)QRSTSRQ(PO)NML(KJ)IHG(FE)DCBA
ABCD(sp)GHI(pd)LMN(de)QRSTSRQ(ed)NML(dp)IHG(ps)DCBA
5. Note: if I give you a sequence that contains "overlapping" ordered pairs like:
...EFK...
then you ignore the second ordered pair. That is, you return:
...(EF)KOK - here is the final stuff on the "C" side.
To execute the program, the command line is:
20let.exe file1.txt file2.txt file3.txt > fileout.txt
Below, I've provided:
a) source code 20let.c
b) sample input file1.txt
c) sample input file2.txt
d) sample input file3.txt
e) output fileout.txt generated from these input files.
As soon as Bill finishes the perl version of the source code, I'll post that also.
source code of 20let.c
// 20let.c5
#include <stdio.h>
#include <stdlib.h>
int T[333],A[99999],G[333],B[99999],C[99999],N[299999],P[99999];
int n1,n2,f,p,x1,x2,n,m,a,b,c,i,j,k,x,y,z;
int E[233][233];
FILE *file;
int substrings(int x1,int x2);
int main(int argc, char*argv[]) {
if(argc<3){
printf("\nusage:20let protein-file nucleotide-file pairs-include-file\n\n");
printf("marks amino-acid-pairs from different groups in protein-file\n");
printf("iff they are in the include-file\n");
exit(1);
//----------------define the groups G['I'] = 's', e.g.
x='s'; G['I']=x;G['M']=x;G['V']=x;G['A']=x;G['G']=x;
x='p'; G['F']=x;G['L']=x;G['P']=x;G['W']=x;G['W']=x;
x='d'; G['H']=x;G['Q']=x;G['D']=x;G['E']=x;G['E']=x;
x='t'; G['S']=x;G['T']=x;G['Y']=x;G['N']=x;G['C']=x;G['K']=x;G['R']=x;
//----------------the 4 bases T['a'] = 0 thru 3
for(x=0;x<222;x++)
T[x]=-999;
T['a']=0;T['c']=1;T['g']=2;T['t']=3;
T['A']=0;T['C']=1;T['G']=2;T['T']=3;
for(i=65;i<70;i++)G<i>='s';
for(i=70;i<75;i++)G<i>='p';
for(i=75;i<80;i++)G<i>='d';
for(i=80;i<85;i++)G<i>='t';
//---------------- read include-file file3 xxxyyy pairs E[x][y] of interest
f=0;
for(x=0;x<222;x++)
for(y=0;y<222;y++)
E[x][y]=0;
if((file=fopen(argv[3],"rb"))==NULL){
printf("\ncan't open exclude-file %s\n",argv[1]);exit(1);
mq1: if(feof(file))
goto mq3;
x=fgetc(file);y=fgetc(file);x=fgetc(file);
x=T[fgetc(file)]*16+T[fgetc(file)]*4+T[fgetc(file)];
y=T[fgetc(file)]*16+T[fgetc(file)]*4+T[fgetc(file)];
if(x<64 && x>=0 && y<64 && y>=0){
E[x][y]=1;
f++;
mq2: if(feof(file))
goto mq3;
a=fgetc(file);
if(a!=10)
goto mq2;
goto mq1;
mq3: fclose(file);
//------------------read amino-acid file file1 == P array
if((file=fopen(argv[1],"rb"))==NULL){
printf("\ncan't open file %s\n",argv[1]);exit(1);}
p=0;
m1p: if(feof(file))
goto m2p;
p++;
P[p]=fgetc(file);
if(G[P[p]]==0)
p--;
goto m1p;
m2p:;
fclose(file);
//------------------read nucleotide file file2 == N array
if((file=fopen(argv[2],"rb"))==NULL){
printf("\ncan't open file %s\n",argv[1]);exit(1);
n=0;
m1n: if(feof(file))
goto m2n;
n++;
N[n]=fgetc(file);
if(N[n]!='a' && N[n]!='c' && N[n]!='g' && N[n]!='t')
n--;
goto m1n;
m2n:;
fclose(file);
//for(i=1;i<=p;i++)printf("%c",P<i>);printf("\n");
//for(i=1;i<=n;i++)printf("%c",N<i>);printf("\n");
//printf("%i include-pairs %i nucleotides %i proteins\n",f,n,p);
//------------1st line------------------ B<i> = result
m=0;
for(i=1;i<=p;i++){
n1=T[N[i*3-2]]*16+T[N[i*3-1]]*4+T[N[i*3]];
n2=T[N[i*3+1]]*16+T[N[i*3+2]]*4+T[N[i*3+3]];
//printf("\ni=%i p=%i n1=%i n2=%i\n",i,p,n1,n2);
if(E[n1][n2]<1 || G[P<i>]==G[P[i+1]] /* || i==n */){
printf("%c",P<i>);
m++;
B[m]=P<i>;
goto m3;
printf("(%c%c)",P<i>,P[i+1]);
i++;
m++;
B[m]='(';
m++;
B[m]=P[i-1];
m++;
B[m]=P<i>;
m++;
B[m]=')';
//printf("(%c)%c",G[A<i>],G[A[i+1]]);i++;
m3:;
printf("\n");
//------------2nd line------------------ C<i> = result
m=0;
for(i=1;i<=p;i++){
n1=T[N[i*3-2]]*16+T[N[i*3-1]]*4+T[N[i*3]];
n2=T[N[i*3+1]]*16+T[N[i*3+2]]*4+T[N[i*3+3]];
if(E[n1][n2]<1 || G[P<i>]==G[P[i+1]] /* || i==n */){
printf("%c",P<i>);
m++;
C[m]=P<i>;
goto m4;
printf("(%c%c)",G[P<i>],G[P[i+1]]);
i++;
m++;
C[m]='(';
m++;
C[m]=G[P[i-1]];
m++;
C[m]=G[P<i>];
m++;
C[m]=')';
//printf("(%c)%c",G[A<i>],G[A[i+1]]);i++;
m4:;
printf("\n");
//for(i=1;i<=m;i++)printf("%c",B<i>);printf("\n");
//------------3rd line------------------ printf only
m=0;
for(i=1;i<=p;i++){
n1=T[N[i*3-2]]*16+T[N[i*3-1]]*4+T[N[i*3]];
n2=T[N[i*3+1]]*16+T[N[i*3+2]]*4+T[N[i*3+3]];
if(E[n1][n2]<1 || G[P<i>]==G[P[i+1]] /* || i==n */){
printf("%c%c%c",N[i*3-2],N[i*3-1],N[i*3]);
goto m33;
printf("(%c%c%c%c%c%c)",N[i*3-2],N[i*3-1],N[i*3],N[i*3+1],N[i*3+2],N[i*3+3]);
i++;
m33:;
printf("\n");
//--------------substrings------------
substrings(20,29);
substrings(30,39);
substrings(40,49);
substrings(50,59);
substrings(60,69);
return 0;
int substrings(int x1,int x2)
printf("\n");
printf("lengths %i - %i : \n",x1,x2);
for(i=1; i<p; i++)
for (j=i+x1; j<i+x2; j++) {
if (C<i>>95 && C[j]>95) { // if lc letter in line2
for(x=i;x<=j;x++)
printf("%c",C[x]);
printf("|");
for(x=i;x<=j;x++)
if(B[x]>44) // if not () in line 1
printf("%c",B[x]);
printf("|");
for(x=i;x<=j;x++)
if(C[x]>95) // if lc letter line2
printf("%c",C[x]);
printf("\n");}
input file1.txt
MKKHTDQPIADVQGSPDTRH
IAIDRVGIKAIRHPVLVADK
DGGSQHTVAQFNMYVNLPHN
FKGTHMSRFVEILNSHEREI
SVESFEEILRSMVSRLESDS
GHIEMTFPYFVNKSAPISGV
KSLLDYEVTFIGEIKHGDQY
GFTMKVIVPVTSLCPCSKKI
SDYGAHNQRSHVTISVHTNS
FVWIEDVIRIAEEQASCELF
GLLKRPDEKYVTEKAYNNPK
FVEDIVRDVAEILNHDDRID
AYVVESEBFESIHNHSAYAL
IERD
input file2.txt
atgaaaaaacatactgatcaacctatcgctgatgtgcagggctcaccggataccagacat
atcgcaattgacagagtcggaatcaaagcgattcgtcacccggttctggtcgccgataag
gatggtggttcccagcataccgtggcgcaatttaatatgtacgtcaatctgccacataat
ttcaaagggacgcatatgtcccgttttgtggagatactaaatagccacgaacgtgaaatt
tcggttgaatcatttgaagaaattttgcgctccatggtcagcaggctggaatcagattcc
ggccatattgaaatgacttttccctacttcgtcaataaatcagcccctatctcaggtgta
aaaagcttgctggattatgaggtaacctttatcggcgaaattaaacatggcgatcaatat
gggtttaccatgaaggtgatcgttcctgttaccagcctgtgcccctgctccaagaaaata
tccgattacggtgcgcataaccagcgttcacacgtcaccatttctgtacacactaacagc
ttcgtctggattgaggacgttatcagaattgcggaagaacaggcctcatgcgaactgttc
ggtctgctgaaacggccggatgaaaaatatgtcacagaaaaggcctataacaatccgaaa
tttgtcgaagatatcgtccgtgatgtcgccgaaatacttaatcatgatgaccggatagat
gcctatgttgttgaatcagaaaactttgaatccatacataatcactctgcatacgcactg
atagagcgcgac
input file3.txt
FA tttgcc
FA ttcgcc
FA tttgct
FA ttcgct
LK ttaaaa
LK ttgaaa
LK ttaaag
LK ttgaag
LS ctgctc
LS ctgctt
LS ctactc
LS ctactt
LT ctcacc
LT ctcact
LT cttacc
LT cttact
LY ctctac
LY ctctat
LY ctttac
LY ctttat
LG ctcggc
LG ctcggt
LG cttggc
LG cttggt
IP attccc
IP attcct
IP atcccc
IP atccct
IP attcca
IP attccg
IP atccca
IP atcccg
ML atgctc
ML atgctt
ML atgctc
ML atgctt
VL gtgctg
VL gtgcta
VL gtactg
VL gtacta
VS gtgtcc
VS gtatct
VS gtgtcc
VS gtatct
VT gtcacc
VT gtcact
VT gttacc
VT gttact
VS gtcagc
VS gtcagt
VS gttagc
VS gttagt
SL tcgctg
SL tcgcta
SL tcactg
SL tcacta
SP tctcca
SP tctccg
SP tcccca
SP tccccg
PV ccggtg
PV ccggta
PV ccagtg
PV ccagta
PG cccggc
PG cccggt
PG cctggc
PG cctggt
TL acgctg
TL acgcta
TL acactg
TL acacta
TP acgccg
TP acgcca
TP acaccg
TP acacca
AL gcttta
AL gctttg
AL gcctta
AL gccttg
AP gcgccg
AP gcgcca
AP gcaccg
AP gcacca
AP gctcca
AP gctccg
AP gcccca
AP gccccg
AN gctaat
AN gctaac
AN gccaat
AN gccaac
AS gccagc
AS gccagt
AS gctagc
AS gctagt
YP tatccg
YP tatcca
YP tacccg
YP taccca
HP catccg
HP catcca
HP cacccg
HP caccca
QR cagcga
QR cagcgg
QR caacga
QR caacgg
DL gatttg
DL gattta
DL gacttg
DL gactta
EN gaaaat
EN gaaaac
EN gagaat
EN gagaac
EK gaaaaa
EK gaaaag
EK gagaaa
EK gagaag
ER gagcga
ER gagcgg
ER gaacga
ER gaacgg
WR tggcga
WR tggcgg
RV cgggtg
RV cgggta
RV cgagtg
RV cgagta
RW cggtgg
RW cgatgg
SG agtgga
SG agtggg
SG agcgga
SG agcggg
GF ggtttt
GF ggtttc
GF ggcttt
GF ggcttc
GL gggctg
GL gggcta
GL ggactg
GL ggacta
GY gggtat
GY gggtac
GY ggatat
GY ggatac
GY ggttat
GY ggttac
GY ggctat
GY ggctac
GK ggaaaa
GK ggaaag
GK gggaaa
GK gggaag
GK ggcaag
GK ggcaaa
GK ggtaag
GK ggtaaa
GW ggctgg
GW ggttgg
GR gggcgg
GR gggcga
GR ggacgg
GR ggacga
GS ggcagc
GS ggcagt
GS ggtagc
GS ggtagt
output fileout.txt
MKKHTDQPIADVQGSPDTRHIAIDRVGIKAIR(HP)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(VS)RLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVP(VT)SLCPCSKKISDYGAHNQRSH(VT)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(EK)YVT(EK)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(EF)ESIHNHSAYALIERD
MKKHTDQPIADVQGSPDTRHIAIDRVGIKAIR(dp)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(st)RLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVP(st)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(dp)ESIHNHSAYALIERD
atgaaaaaacatactgatcaacctatcgctgatgtgcagggctcaccggataccagacatatcgcaattgacagagtcggaatcaaagcgattcgt(cacccg)gttctggtcgccgataaggatggtggttcccagcataccgtggcgcaatttaatatgtacgtcaatctgccacataatttcaaagggacgcatatgtcccgttttgtggagatactaaatagccacgaacgtgaaatttcggttgaatcatttgaagaaattttgcgctccatg(gtcagc)aggctggaatcagattccggccatattgaaatgacttttccctacttcgtcaataaatcagcccctatctcaggtgtaaaaagcttgctggattatgaggtaacctttatcggcgaaattaaacatggcgatcaatatgggtttaccatgaaggtgatcgttcct(gttacc)agcctgtgcccctgctccaagaaaatatccgattacggtgcgcataaccagcgttcacac(gtcacc)atttctgtacacactaacagcttcgtctggattgaggacgttatcagaattgcggaagaacaggcctcatgcgaactgttcggtctgctgaaacggccggat(gaaaaa)tatgtcaca(gaaaag)gcctataacaatccgaaatttgtcgaagatatcgtccgtgatgtcgccgaaatacttaatcatgatgaccggatagatgcctatgttgttgaatca(gaaaac)tttgaatccatacataatcactctgcatacgcactgatagagcgc
lengths 20 - 29 :
st)SLCPCSKKISDYGAHNQRSH(s|VTSLCPCSKKISDYGAHNQRSHV|sts
st)SLCPCSKKISDYGAHNQRSH(st|VTSLCPCSKKISDYGAHNQRSHVT|stst
t)SLCPCSKKISDYGAHNQRSH(s|TSLCPCSKKISDYGAHNQRSHV|ts
t)SLCPCSKKISDYGAHNQRSH(st|TSLCPCSKKISDYGAHNQRSHVT|tst
lengths 30 - 39 :
st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(d|VTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDE|std
t)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(d|TISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDE|td
t)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt|TISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEK|tdt
dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(d|EKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESE|dtd
dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(dp|EKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESEF|dtdp
t)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(d|KAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESE|td
t)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(dp|KAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESEF|tdp
lengths 40 - 49 :
st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(d|VTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEKYVTE|stdtd
st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(dt|VTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEKYVTEK|stdtdt
t)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(d|TISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEKYVTE|tdtd
t)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(dt|TISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEKYVTEK|tdtdt
dt)YVT(dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(d|EKYVTEKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESE|dtdtd
dt)YVT(dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(dp|EKYVTEKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESEF|dtdtdp
t)YVT(dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(d|KYVTEKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESE|tdtd
t)YVT(dt)AYNNPKFVEDIVRDVAEILNHDDRIDAYVVES(dp|KYVTEKAYNNPKFVEDIVRDVAEILNHDDRIDAYVVESEF|tdtdp
lengths 50 - 59 :
t)RLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVP(s|SRLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVPV|ts
lengths 60 - 69 :
dp)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(s|HPVLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSMV|dps
dp)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(st|HPVLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSMVS|dpst
p)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(s|PVLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSMV|ps
p)VLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSM(st|PVLVADKDGGSQHTVAQFNMYVNLPHNFKGTHMSRFVEILNSHEREISVESFEEILRSMVS|pst
st)RLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVP(st|VSRLESDSGHIEMTFPYFVNKSAPISGVKSLLDYEVTFIGEIKHGDQYGFTMKVIVPVT|stst
st)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(d|VTSLCPCSKKISDYGAHNQRSHVTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDE|ststd
st)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt|VTSLCPCSKKISDYGAHNQRSHVTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEK|ststdt
t)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(d|TSLCPCSKKISDYGAHNQRSHVTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDE|tstd
t)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt|TSLCPCSKKISDYGAHNQRSHVTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEK|tstdt
t)SLCPCSKKISDYGAHNQRSH(st)ISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPD(dt)YVT(d|TSLCPCSKKISDYGAHNQRSHVTISVHTNSFVWIEDVIRIAEEQASCELFGLLKRPDEKYVTE|tstdtd
Edited by: David Halitsky on Mar 18, 2008 4:21 AM
Edited by: David Halitsky on Mar 18, 2008 4:22 AM -
Hi All,
i've a string holding the value as given below.
AA,17,2/19/2003,"9,999.00",USD,00,10,318,"193,275.31"
by performing some string operations i want the result string in the format as given below:
AA,17,2/19/2003,"9999.00",USD,00,10,318,"193,275.31"
i.e., i want to remove all the commas(,)that are included in between a pair of " " only.
can anyone provide me a sample code for the sameHi vijay,
A bit complex but works for sure, check the following logic,
REPORT zsritest.
DATA: gs_string TYPE string.
gs_string = 'AA,17,2/19/2003,"9,999.00",USD,00,10,318,"193,275.31"'.
WRITE: / gs_string.
PERFORM string_trim CHANGING gs_string.
* FORM string_trim *
* --> LS_STRING *
FORM string_trim CHANGING ls_string.
DATA: lt_string TYPE string OCCURS 0 WITH HEADER LINE,
lv_tabix TYPE i,
lv_start.
SPLIT gs_string AT '"' INTO TABLE lt_string.
CHECK sy-subrc EQ 0.
CLEAR gs_string.
LOOP AT lt_string.
lv_tabix = sy-tabix MOD 2.
IF lv_tabix EQ 0.
TRANSLATE lt_string USING ', '.
CONDENSE lt_string NO-GAPS.
ENDIF.
IF lv_tabix EQ 0 OR lv_start EQ 'X'.
CONCATENATE gs_string lt_string INTO gs_string SEPARATED BY '"'.
IF lv_start EQ 'X'.
CLEAR lv_start.
ELSE.
lv_start = 'X'.
ENDIF.
ELSE.
CONCATENATE gs_string lt_string INTO gs_string.
ENDIF.
ENDLOOP.
IF lv_start EQ 'X'.
CONCATENATE gs_string '"' INTO gs_string.
ENDIF.
WRITE: / gs_string.
ENDFORM.
Hope this helps..
Sri -
Need help in String operations
HI all,
I need help in String operations.I am getting file path of an image as
c:\test\img\abc.gif"
I need to convert it in to c:/test/img/abc.gif".
Can any one suggest the solution for this.
Thanks,
Durga.[email protected] wrote:
I used String replace method but I am not able to do it because "/" is a special character."/" is not a special character, "\" is a special character, which needs to be escaped by "\" itself. -
Please tell the basic procedure and operations for inventory in Sap
Hello:
everybody, please tell me the basic procedure and operations for inventory
in sap? couldn't thank you more.
Frank
Best regardshttp://help.sap.com/printdocu/core/Print46c/en/data/pdf/MMIM/MMIM.pdf
/people/community.user/blog/2007/05/04/physical-inventory-in-material-management
Physical Inventory Cycle:
1. Create physical Inventory document MI01
2. Print physical inventory document MI21
3. Enter count MI04
4. Execute difference list MI20
5. Post with/without differences MI07
Configuration :
Inventory Management and Physical Inventory
Plant Parameters for inventory management
Goods receipt: Set tolerance limit
Valuation and Account Determination
Define Price Control for Material Types
Account Determination without Wizard
Rewards if Helpful -
I'm half way through writing a web interface for mpd. I needed a way to interact with it so I searched around and found this. It's a php class that interfaces with mpd.
I downloaded it and it comes with an example php file for using it. The only problem is that when I use the example page it just prints out anything after the arrow operator. As far as I'm aware the arrow operator is for accessing class methods and variables but I've never actually done any OOP with PHP.
Anyway here is the example file:
<?
* mpd-class-example.php - Example interface using mpd.class.php
* Version 1.2, released 05/05/2004
* Copyright (C) 2003-2004 Benjamin Carlisle ([email protected])
* http://mpd.24oz.com/ | http://www.musicpd.org/
* This program illustrates the basic commands and usage of the MPD class.
* *** PLEASE NOTE *** My intention in including this file is not to provide you with an
* out-of-the-box MPD jukebox, but instead to provide a general understanding of how I saw
* the class as being utilized. If you'd like to see more examples, please let me know. But
* this should provide you with a good starting point for your own program development.
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
?>
<HTML>
<style type="text/css"><!-- .defaultText { font-family: Arial, Helvetica, sans-serif; font-size: 9pt; font-style: normal; font-weight: normal; color: #111111} .err { color: #DD3333 } --></style>
<BODY class="defaultText">
<?
include('mpd.class.php');
$myMpd = new mpd('localhost',2100);
if ( $myMpd->connected == FALSE ) {
echo "Error Connecting: " . $myMpd->errStr;
} else {
switch ($_REQUEST[m]) {
case "add":
if ( is_null($myMpd->PLAdd($_REQUEST[filename])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "rem":
if ( is_null($myMpd->PLRemove($_REQUEST[id])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "setvol":
if ( is_null($myMpd->SetVolume($_REQUEST[vol])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "play":
if ( is_null($myMpd->Play()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "stop":
if ( is_null($myMpd->Stop()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "pause":
if ( is_null($myMpd->Pause()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
default:
break;
?>
<DIV ALIGN=CENTER>[ <A HREF="<? echo $_SERVER[PHP_SELF] ?>">Refresh Page</A> ]</DIV>
<HR>
<B>Connected to MPD Version <? echo $myMpd->mpd_version ?> at <? echo $myMpd->host ?>:<? echo $myMpd->port ?></B><BR>
State:
<?
switch ($myMpd->state) {
case MPD_STATE_PLAYING: echo "MPD is Playing [<A HREF='".$_SERVER[PHP_SELF]."?m=pause'>Pause</A>] [<A HREF='".$_SERVER[PHP_SELF]."?m=stop'>Stop</A>]"; break;
case MPD_STATE_PAUSED: echo "MPD is Paused [<A HREF='".$_SERVER[PHP_SELF]."?m=pause'>Unpause</A>]"; break;
case MPD_STATE_STOPPED: echo "MPD is Stopped [<A HREF='".$_SERVER[PHP_SELF]."?m=play'>Play</A>]"; break;
default: echo "(Unknown State!)"; break;
?>
<BR>
Volume: <? echo $myMpd->volume ?> [ <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=0'>0</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=25'>25</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=75'>75</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=100'>100</A> ]<BR>
Uptime: <? echo secToTimeStr($myMpd->uptime) ?><BR>
Playtime: <? echo secToTimeStr($myMpd->playtime) ?><BR>
<? if ( $myMpd->state == MPD_STATE_PLAYING or $myMpd->state == MPD_STATE_PAUSED ) { ?>
Currently Playing: <? echo $myMpd->playlist[$myMpd->current_track_id]['Artist']." - ".$myMpd->playlist[$myMpd->current_track_id]['Title'] ?><BR>
Track Position: <? echo $myMpd->current_track_position."/".$myMpd->current_track_length." (".(round(($myMpd->current_track_position/$myMpd->current_track_length),2)*100)."%)" ?><BR>
Playlist Position: <? echo ($myMpd->current_track_id+1)."/".$myMpd->playlist_count." (".(round((($myMpd->current_track_id+1)/$myMpd->playlist_count),2)*100)."%)" ?><BR>
<? } ?>
<HR>
<B>Playlist - Total: <? echo $myMpd->playlist_count ?> tracks (Click to Remove)</B><BR>
<?
if ( is_null($myMpd->playlist) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
foreach ($myMpd->playlist as $id => $entry) {
echo ( $id == $myMpd->current_track_id ? "<B>" : "" ) . ($id+1) . ". <A HREF='".$_SERVER[PHP_SELF]."?m=rem&id=".$id."'>".$entry['Artist']." - ".$entry['Title']."</A>".( $id == $myMpd->current_track_id ? "</B>" : "" )."<BR>\n";
?>
<HR>
<B>Sample Search for the String 'U2' (Click to Add to Playlist)</B><BR>
<?
$sl = $myMpd->Search(MPD_SEARCH_ARTIST,'U2');
if ( is_null($sl) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
foreach ($sl as $id => $entry) {
echo ($id+1) . ": <A HREF='".$_SERVER[PHP_SELF]."?m=add&filename=".urlencode($entry['file'])."'>".$entry['Artist']." - ".$entry['Title']."</A><BR>\n";
if ( count($sl) == 0 ) echo "<I>No results returned from search.</I>";
// Example of how you would use Bulk Add features of MPD
// $myarray = array();
// $myarray[0] = "ACDC - Thunderstruck.mp3";
// $myarray[1] = "ACDC - Back In Black.mp3";
// $myarray[2] = "ACDC - Hells Bells.mp3";
// if ( is_null($myMpd->PLAddBulk($myarray)) ) echo "ERROR: ".$myMpd->errStr."\n";
?>
<HR>
<B>Artist List</B><BR>
<?
if ( is_null($ar = $myMpd->GetArtists()) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
while(list($key, $value) = each($ar) ) {
echo ($key+1) . ". " . $value . "<BR>";
$myMpd->Disconnect();
// Used to make number of seconds perty.
function secToTimeStr($secs) {
$days = ($secs%604800)/86400;
$hours = (($secs%604800)%86400)/3600;
$minutes = ((($secs%604800)%86400)%3600)/60;
$seconds = (((($secs%604800)%86400)%3600)%60);
if (round($days)) $timestring .= round($days)."d ";
if (round($hours)) $timestring .= round($hours)."h ";
if (round($minutes)) $timestring .= round($minutes)."m";
if (!round($minutes)&&!round($hours)&&!round($days)) $timestring.=" ".round($seconds)."s";
return $timestring;
?>
</BODY></HTML>
The class file:
<?php
* mpd.class.php - PHP Object Interface to the MPD Music Player Daemon
* Version 1.2, Released 05/05/2004
* Copyright (C) 2003-2004 Benjamin Carlisle ([email protected])
* http://mpd.24oz.com/ | http://www.musicpd.org/
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Create common command definitions for MPD to use
define("MPD_CMD_STATUS", "status");
define("MPD_CMD_STATISTICS", "stats");
define("MPD_CMD_VOLUME", "volume");
define("MPD_CMD_SETVOL", "setvol");
define("MPD_CMD_PLAY", "play");
define("MPD_CMD_STOP", "stop");
define("MPD_CMD_PAUSE", "pause");
define("MPD_CMD_NEXT", "next");
define("MPD_CMD_PREV", "previous");
define("MPD_CMD_PLLIST", "playlistinfo");
define("MPD_CMD_PLADD", "add");
define("MPD_CMD_PLREMOVE", "delete");
define("MPD_CMD_PLCLEAR", "clear");
define("MPD_CMD_PLSHUFFLE", "shuffle");
define("MPD_CMD_PLLOAD", "load");
define("MPD_CMD_PLSAVE", "save");
define("MPD_CMD_KILL", "kill");
define("MPD_CMD_REFRESH", "update");
define("MPD_CMD_REPEAT", "repeat");
define("MPD_CMD_LSDIR", "lsinfo");
define("MPD_CMD_SEARCH", "search");
define("MPD_CMD_START_BULK", "command_list_begin");
define("MPD_CMD_END_BULK", "command_list_end");
define("MPD_CMD_FIND", "find");
define("MPD_CMD_RANDOM", "random");
define("MPD_CMD_SEEK", "seek");
define("MPD_CMD_PLSWAPTRACK", "swap");
define("MPD_CMD_PLMOVETRACK", "move");
define("MPD_CMD_PASSWORD", "password");
define("MPD_CMD_TABLE", "list");
// Predefined MPD Response messages
define("MPD_RESPONSE_ERR", "ACK");
define("MPD_RESPONSE_OK", "OK");
// MPD State Constants
define("MPD_STATE_PLAYING", "play");
define("MPD_STATE_STOPPED", "stop");
define("MPD_STATE_PAUSED", "pause");
// MPD Searching Constants
define("MPD_SEARCH_ARTIST", "artist");
define("MPD_SEARCH_TITLE", "title");
define("MPD_SEARCH_ALBUM", "album");
// MPD Cache Tables
define("MPD_TBL_ARTIST","artist");
define("MPD_TBL_ALBUM","album");
class mpd {
// TCP/Connection variables
var $host;
var $port;
var $password;
var $mpd_sock = NULL;
var $connected = FALSE;
// MPD Status variables
var $mpd_version = "(unknown)";
var $state;
var $current_track_position;
var $current_track_length;
var $current_track_id;
var $volume;
var $repeat;
var $random;
var $uptime;
var $playtime;
var $db_last_refreshed;
var $num_songs_played;
var $playlist_count;
var $num_artists;
var $num_albums;
var $num_songs;
var $playlist = array();
// Misc Other Vars
var $mpd_class_version = "1.2";
var $debugging = FALSE; // Set to TRUE to turn extended debugging on.
var $errStr = ""; // Used for maintaining information about the last error message
var $command_queue; // The list of commands for bulk command sending
// =================== BEGIN OBJECT METHODS ================
/* mpd() : Constructor
* Builds the MPD object, connects to the server, and refreshes all local object properties.
function mpd($srv,$port,$pwd = NULL) {
$this->host = $srv;
$this->port = $port;
$this->password = $pwd;
$resp = $this->Connect();
if ( is_null($resp) ) {
$this->errStr = "Could not connect";
return;
} else {
list ( $this->mpd_version ) = sscanf($resp, MPD_RESPONSE_OK . " MPD %s\n");
if ( ! is_null($pwd) ) {
if ( is_null($this->SendCommand(MPD_CMD_PASSWORD,$pwd)) ) {
$this->connected = FALSE;
return; // bad password or command
if ( is_null($this->RefreshInfo()) ) { // no read access -- might as well be disconnected!
$this->connected = FALSE;
$this->errStr = "Password supplied does not have read access";
return;
} else {
if ( is_null($this->RefreshInfo()) ) { // no read access -- might as well be disconnected!
$this->connected = FALSE;
$this->errStr = "Password required to access server";
return;
/* Connect()
* Connects to the MPD server.
* NOTE: This is called automatically upon object instantiation; you should not need to call this directly.
function Connect() {
if ( $this->debugging ) echo "mpd->Connect() / host: ".$this->host.", port: ".$this->port."\n";
$this->mpd_sock = fsockopen($this->host,$this->port,$errNo,$errStr,10);
if (!$this->mpd_sock) {
$this->errStr = "Socket Error: $errStr ($errNo)";
return NULL;
} else {
while(!feof($this->mpd_sock)) {
$response = fgets($this->mpd_sock,1024);
if (strncmp(MPD_RESPONSE_OK,$response,strlen(MPD_RESPONSE_OK)) == 0) {
$this->connected = TRUE;
return $response;
break;
if (strncmp(MPD_RESPONSE_ERR,$response,strlen(MPD_RESPONSE_ERR)) == 0) {
$this->errStr = "Server responded with: $response";
return NULL;
// Generic response
$this->errStr = "Connection not available";
return NULL;
/* SendCommand()
* Sends a generic command to the MPD server. Several command constants are pre-defined for
* use (see MPD_CMD_* constant definitions above).
function SendCommand($cmdStr,$arg1 = "",$arg2 = "") {
if ( $this->debugging ) echo "mpd->SendCommand() / cmd: ".$cmdStr.", args: ".$arg1." ".$arg2."\n";
if ( ! $this->connected ) {
echo "mpd->SendCommand() / Error: Not connected\n";
} else {
// Clear out the error String
$this->errStr = "";
$respStr = "";
// Check the command compatibility:
if ( ! $this->_checkCompatibility($cmdStr) ) {
return NULL;
if (strlen($arg1) > 0) $cmdStr .= " \"$arg1\"";
if (strlen($arg2) > 0) $cmdStr .= " \"$arg2\"";
fputs($this->mpd_sock,"$cmdStr\n");
while(!feof($this->mpd_sock)) {
$response = fgets($this->mpd_sock,1024);
// An OK signals the end of transmission -- we'll ignore it
if (strncmp(MPD_RESPONSE_OK,$response,strlen(MPD_RESPONSE_OK)) == 0) {
break;
// An ERR signals the end of transmission with an error! Let's grab the single-line message.
if (strncmp(MPD_RESPONSE_ERR,$response,strlen(MPD_RESPONSE_ERR)) == 0) {
list ( $junk, $errTmp ) = split(MPD_RESPONSE_ERR . " ",$response );
$this->errStr = strtok($errTmp,"\n");
if ( strlen($this->errStr) > 0 ) {
return NULL;
// Build the response string
$respStr .= $response;
if ( $this->debugging ) echo "mpd->SendCommand() / response: '".$respStr."'\n";
return $respStr;
/* QueueCommand()
* Queues a generic command for later sending to the MPD server. The CommandQueue can hold
* as many commands as needed, and are sent all at once, in the order they are queued, using
* the SendCommandQueue() method. The syntax for queueing commands is identical to SendCommand().
function QueueCommand($cmdStr,$arg1 = "",$arg2 = "") {
if ( $this->debugging ) echo "mpd->QueueCommand() / cmd: ".$cmdStr.", args: ".$arg1." ".$arg2."\n";
if ( ! $this->connected ) {
echo "mpd->QueueCommand() / Error: Not connected\n";
return NULL;
} else {
if ( strlen($this->command_queue) == 0 ) {
$this->command_queue = MPD_CMD_START_BULK . "\n";
if (strlen($arg1) > 0) $cmdStr .= " \"$arg1\"";
if (strlen($arg2) > 0) $cmdStr .= " \"$arg2\"";
$this->command_queue .= $cmdStr ."\n";
if ( $this->debugging ) echo "mpd->QueueCommand() / return\n";
return TRUE;
/* SendCommandQueue()
* Sends all commands in the Command Queue to the MPD server. See also QueueCommand().
function SendCommandQueue() {
if ( $this->debugging ) echo "mpd->SendCommandQueue()\n";
if ( ! $this->connected ) {
echo "mpd->SendCommandQueue() / Error: Not connected\n";
return NULL;
} else {
$this->command_queue .= MPD_CMD_END_BULK . "\n";
if ( is_null($respStr = $this->SendCommand($this->command_queue)) ) {
return NULL;
} else {
$this->command_queue = NULL;
if ( $this->debugging ) echo "mpd->SendCommandQueue() / response: '".$respStr."'\n";
return $respStr;
/* AdjustVolume()
* Adjusts the mixer volume on the MPD by <modifier>, which can be a positive (volume increase),
* or negative (volume decrease) value.
function AdjustVolume($modifier) {
if ( $this->debugging ) echo "mpd->AdjustVolume()\n";
if ( ! is_numeric($modifier) ) {
$this->errStr = "AdjustVolume() : argument 1 must be a numeric value";
return NULL;
$this->RefreshInfo();
$newVol = $this->volume + $modifier;
$ret = $this->SetVolume($newVol);
if ( $this->debugging ) echo "mpd->AdjustVolume() / return\n";
return $ret;
/* SetVolume()
* Sets the mixer volume to <newVol>, which should be between 1 - 100.
function SetVolume($newVol) {
if ( $this->debugging ) echo "mpd->SetVolume()\n";
if ( ! is_numeric($newVol) ) {
$this->errStr = "SetVolume() : argument 1 must be a numeric value";
return NULL;
// Forcibly prevent out of range errors
if ( $newVol < 0 ) $newVol = 0;
if ( $newVol > 100 ) $newVol = 100;
// If we're not compatible with SETVOL, we'll try adjusting using VOLUME
if ( $this->_checkCompatibility(MPD_CMD_SETVOL) ) {
if ( ! is_null($ret = $this->SendCommand(MPD_CMD_SETVOL,$newVol))) $this->volume = $newVol;
} else {
$this->RefreshInfo(); // Get the latest volume
if ( is_null($this->volume) ) {
return NULL;
} else {
$modifier = ( $newVol - $this->volume );
if ( ! is_null($ret = $this->SendCommand(MPD_CMD_VOLUME,$modifier))) $this->volume = $newVol;
if ( $this->debugging ) echo "mpd->SetVolume() / return\n";
return $ret;
/* GetDir()
* Retrieves a database directory listing of the <dir> directory and places the results into
* a multidimensional array. If no directory is specified, the directory listing is at the
* base of the MPD music path.
function GetDir($dir = "") {
if ( $this->debugging ) echo "mpd->GetDir()\n";
$resp = $this->SendCommand(MPD_CMD_LSDIR,$dir);
$dirlist = $this->_parseFileListResponse($resp);
if ( $this->debugging ) echo "mpd->GetDir() / return ".print_r($dirlist)."\n";
return $dirlist;
/* PLAdd()
* Adds each track listed in a single-dimensional <trackArray>, which contains filenames
* of tracks to add, to the end of the playlist. This is used to add many, many tracks to
* the playlist in one swoop.
function PLAddBulk($trackArray) {
if ( $this->debugging ) echo "mpd->PLAddBulk()\n";
$num_files = count($trackArray);
for ( $i = 0; $i < $num_files; $i++ ) {
$this->QueueCommand(MPD_CMD_PLADD,$trackArray[$i]);
$resp = $this->SendCommandQueue();
$this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLAddBulk() / return\n";
return $resp;
/* PLAdd()
* Adds the file <file> to the end of the playlist. <file> must be a track in the MPD database.
function PLAdd($fileName) {
if ( $this->debugging ) echo "mpd->PLAdd()\n";
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLADD,$fileName))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLAdd() / return\n";
return $resp;
/* PLMoveTrack()
* Moves track number <origPos> to position <newPos> in the playlist. This is used to reorder
* the songs in the playlist.
function PLMoveTrack($origPos, $newPos) {
if ( $this->debugging ) echo "mpd->PLMoveTrack()\n";
if ( ! is_numeric($origPos) ) {
$this->errStr = "PLMoveTrack(): argument 1 must be numeric";
return NULL;
if ( $origPos < 0 or $origPos > $this->playlist_count ) {
$this->errStr = "PLMoveTrack(): argument 1 out of range";
return NULL;
if ( $newPos < 0 ) $newPos = 0;
if ( $newPos > $this->playlist_count ) $newPos = $this->playlist_count;
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLMOVETRACK,$origPos,$newPos))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLMoveTrack() / return\n";
return $resp;
/* PLShuffle()
* Randomly reorders the songs in the playlist.
function PLShuffle() {
if ( $this->debugging ) echo "mpd->PLShuffle()\n";
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLSHUFFLE))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLShuffle() / return\n";
return $resp;
/* PLLoad()
* Retrieves the playlist from <file>.m3u and loads it into the current playlist.
function PLLoad($file) {
if ( $this->debugging ) echo "mpd->PLLoad()\n";
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLLOAD,$file))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLLoad() / return\n";
return $resp;
/* PLSave()
* Saves the playlist to <file>.m3u for later retrieval. The file is saved in the MPD playlist
* directory.
function PLSave($file) {
if ( $this->debugging ) echo "mpd->PLSave()\n";
$resp = $this->SendCommand(MPD_CMD_PLSAVE,$file);
if ( $this->debugging ) echo "mpd->PLSave() / return\n";
return $resp;
/* PLClear()
* Empties the playlist.
function PLClear() {
if ( $this->debugging ) echo "mpd->PLClear()\n";
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLCLEAR))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLClear() / return\n";
return $resp;
/* PLRemove()
* Removes track <id> from the playlist.
function PLRemove($id) {
if ( $this->debugging ) echo "mpd->PLRemove()\n";
if ( ! is_numeric($id) ) {
$this->errStr = "PLRemove() : argument 1 must be a numeric value";
return NULL;
if ( ! is_null($resp = $this->SendCommand(MPD_CMD_PLREMOVE,$id))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->PLRemove() / return\n";
return $resp;
/* SetRepeat()
* Enables 'loop' mode -- tells MPD continually loop the playlist. The <repVal> parameter
* is either 1 (on) or 0 (off).
function SetRepeat($repVal) {
if ( $this->debugging ) echo "mpd->SetRepeat()\n";
$rpt = $this->SendCommand(MPD_CMD_REPEAT,$repVal);
$this->repeat = $repVal;
if ( $this->debugging ) echo "mpd->SetRepeat() / return\n";
return $rpt;
/* SetRandom()
* Enables 'randomize' mode -- tells MPD to play songs in the playlist in random order. The
* <rndVal> parameter is either 1 (on) or 0 (off).
function SetRandom($rndVal) {
if ( $this->debugging ) echo "mpd->SetRandom()\n";
$resp = $this->SendCommand(MPD_CMD_RANDOM,$rndVal);
$this->random = $rndVal;
if ( $this->debugging ) echo "mpd->SetRandom() / return\n";
return $resp;
/* Shutdown()
* Shuts down the MPD server (aka sends the KILL command). This closes the current connection,
* and prevents future communication with the server.
function Shutdown() {
if ( $this->debugging ) echo "mpd->Shutdown()\n";
$resp = $this->SendCommand(MPD_CMD_SHUTDOWN);
$this->connected = FALSE;
unset($this->mpd_version);
unset($this->errStr);
unset($this->mpd_sock);
if ( $this->debugging ) echo "mpd->Shutdown() / return\n";
return $resp;
/* DBRefresh()
* Tells MPD to rescan the music directory for new tracks, and to refresh the Database. Tracks
* cannot be played unless they are in the MPD database.
function DBRefresh() {
if ( $this->debugging ) echo "mpd->DBRefresh()\n";
$resp = $this->SendCommand(MPD_CMD_REFRESH);
// Update local variables
$this->RefreshInfo();
if ( $this->debugging ) echo "mpd->DBRefresh() / return\n";
return $resp;
/* Play()
* Begins playing the songs in the MPD playlist.
function Play() {
if ( $this->debugging ) echo "mpd->Play()\n";
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_PLAY) )) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->Play() / return\n";
return $rpt;
/* Stop()
* Stops playing the MPD.
function Stop() {
if ( $this->debugging ) echo "mpd->Stop()\n";
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_STOP) )) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->Stop() / return\n";
return $rpt;
/* Pause()
* Toggles pausing on the MPD. Calling it once will pause the player, calling it again
* will unpause.
function Pause() {
if ( $this->debugging ) echo "mpd->Pause()\n";
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_PAUSE) )) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->Pause() / return\n";
return $rpt;
/* SeekTo()
* Skips directly to the <idx> song in the MPD playlist.
function SkipTo($idx) {
if ( $this->debugging ) echo "mpd->SkipTo()\n";
if ( ! is_numeric($idx) ) {
$this->errStr = "SkipTo() : argument 1 must be a numeric value";
return NULL;
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_PLAY,$idx))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->SkipTo() / return\n";
return $idx;
/* SeekTo()
* Skips directly to a given position within a track in the MPD playlist. The <pos> argument,
* given in seconds, is the track position to locate. The <track> argument, if supplied is
* the track number in the playlist. If <track> is not specified, the current track is assumed.
function SeekTo($pos, $track = -1) {
if ( $this->debugging ) echo "mpd->SeekTo()\n";
if ( ! is_numeric($pos) ) {
$this->errStr = "SeekTo() : argument 1 must be a numeric value";
return NULL;
if ( ! is_numeric($track) ) {
$this->errStr = "SeekTo() : argument 2 must be a numeric value";
return NULL;
if ( $track == -1 ) {
$track = $this->current_track_id;
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_SEEK,$track,$pos))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->SeekTo() / return\n";
return $pos;
/* Next()
* Skips to the next song in the MPD playlist. If not playing, returns an error.
function Next() {
if ( $this->debugging ) echo "mpd->Next()\n";
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_NEXT))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->Next() / return\n";
return $rpt;
/* Previous()
* Skips to the previous song in the MPD playlist. If not playing, returns an error.
function Previous() {
if ( $this->debugging ) echo "mpd->Previous()\n";
if ( ! is_null($rpt = $this->SendCommand(MPD_CMD_PREV))) $this->RefreshInfo();
if ( $this->debugging ) echo "mpd->Previous() / return\n";
return $rpt;
/* Search()
* Searches the MPD database. The search <type> should be one of the following:
* MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM
* The search <string> is a case-insensitive locator string. Anything that contains
* <string> will be returned in the results.
function Search($type,$string) {
if ( $this->debugging ) echo "mpd->Search()\n";
if ( $type != MPD_SEARCH_ARTIST and
$type != MPD_SEARCH_ALBUM and
$type != MPD_SEARCH_TITLE ) {
$this->errStr = "mpd->Search(): invalid search type";
return NULL;
} else {
if ( is_null($resp = $this->SendCommand(MPD_CMD_SEARCH,$type,$string))) return NULL;
$searchlist = $this->_parseFileListResponse($resp);
if ( $this->debugging ) echo "mpd->Search() / return ".print_r($searchlist)."\n";
return $searchlist;
/* Find()
* Find() looks for exact matches in the MPD database. The find <type> should be one of
* the following:
* MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM
* The find <string> is a case-insensitive locator string. Anything that exactly matches
* <string> will be returned in the results.
function Find($type,$string) {
if ( $this->debugging ) echo "mpd->Find()\n";
if ( $type != MPD_SEARCH_ARTIST and
$type != MPD_SEARCH_ALBUM and
$type != MPD_SEARCH_TITLE ) {
$this->errStr = "mpd->Find(): invalid find type";
return NULL;
} else {
if ( is_null($resp = $this->SendCommand(MPD_CMD_FIND,$type,$string))) return NULL;
$searchlist = $this->_parseFileListResponse($resp);
if ( $this->debugging ) echo "mpd->Find() / return ".print_r($searchlist)."\n";
return $searchlist;
/* Disconnect()
* Closes the connection to the MPD server.
function Disconnect() {
if ( $this->debugging ) echo "mpd->Disconnect()\n";
fclose($this->mpd_sock);
$this->connected = FALSE;
unset($this->mpd_version);
unset($this->errStr);
unset($this->mpd_sock);
/* GetArtists()
* Returns the list of artists in the database in an associative array.
function GetArtists() {
if ( $this->debugging ) echo "mpd->GetArtists()\n";
if ( is_null($resp = $this->SendCommand(MPD_CMD_TABLE, MPD_TBL_ARTIST))) return NULL;
$arArray = array();
$arLine = strtok($resp,"\n");
$arName = "";
$arCounter = -1;
while ( $arLine ) {
list ( $element, $value ) = split(": ",$arLine);
if ( $element == "Artist" ) {
$arCounter++;
$arName = $value;
$arArray[$arCounter] = $arName;
$arLine = strtok("\n");
if ( $this->debugging ) echo "mpd->GetArtists()\n";
return $arArray;
/* GetAlbums()
* Returns the list of albums in the database in an associative array. Optional parameter
* is an artist Name which will list all albums by a particular artist.
function GetAlbums( $ar = NULL) {
if ( $this->debugging ) echo "mpd->GetAlbums()\n";
if ( is_null($resp = $this->SendCommand(MPD_CMD_TABLE, MPD_TBL_ALBUM, $ar ))) return NULL;
$alArray = array();
$alLine = strtok($resp,"\n");
$alName = "";
$alCounter = -1;
while ( $alLine ) {
list ( $element, $value ) = split(": ",$alLine);
if ( $element == "Album" ) {
$alCounter++;
$alName = $value;
$alArray[$alCounter] = $alName;
$alLine = strtok("\n");
if ( $this->debugging ) echo "mpd->GetAlbums()\n";
return $alArray;
//***************************** INTERNAL FUNCTIONS ******************************//
/* _computeVersionValue()
* Computes a compatibility value from a version string
function _computeVersionValue($verStr) {
list ($ver_maj, $ver_min, $ver_rel ) = split("\.",$verStr);
return ( 100 * $ver_maj ) + ( 10 * $ver_min ) + ( $ver_rel );
/* _checkCompatibility()
* Check MPD command compatibility against our internal table. If there is no version
* listed in the table, allow it by default.
function _checkCompatibility($cmd) {
// Check minimum compatibility
$req_ver_low = $this->COMPATIBILITY_MIN_TBL[$cmd];
$req_ver_hi = $this->COMPATIBILITY_MAX_TBL[$cmd];
$mpd_ver = $this->_computeVersionValue($this->mpd_version);
if ( $req_ver_low ) {
$req_ver = $this->_computeVersionValue($req_ver_low);
if ( $mpd_ver < $req_ver ) {
$this->errStr = "Command '$cmd' is not compatible with this version of MPD, version ".$req_ver_low." required";
return FALSE;
// Check maxmum compatibility -- this will check for deprecations
if ( $req_ver_hi ) {
$req_ver = $this->_computeVersionValue($req_ver_hi);
if ( $mpd_ver > $req_ver ) {
$this->errStr = "Command '$cmd' has been deprecated in this version of MPD.";
return FALSE;
return TRUE;
/* _parseFileListResponse()
* Builds a multidimensional array with MPD response lists.
* NOTE: This function is used internally within the class. It should not be used.
function _parseFileListResponse($resp) {
if ( is_null($resp) ) {
return NULL;
} else {
$plistArray = array();
$plistLine = strtok($resp,"\n");
$plistFile = "";
$plCounter = -1;
while ( $plistLine ) {
list ( $element, $value ) = split(": ",$plistLine);
if ( $element == "file" ) {
$plCounter++;
$plistFile = $value;
$plistArray[$plCounter]["file"] = $plistFile;
} else {
$plistArray[$plCounter][$element] = $value;
$plistLine = strtok("\n");
return $plistArray;
/* RefreshInfo()
* Updates all class properties with the values from the MPD server.
* NOTE: This function is automatically called upon Connect() as of v1.1.
function RefreshInfo() {
// Get the Server Statistics
$statStr = $this->SendCommand(MPD_CMD_STATISTICS);
if ( !$statStr ) {
return NULL;
} else {
$stats = array();
$statLine = strtok($statStr,"\n");
while ( $statLine ) {
list ( $element, $value ) = split(": ",$statLine);
$stats[$element] = $value;
$statLine = strtok("\n");
// Get the Server Status
$statusStr = $this->SendCommand(MPD_CMD_STATUS);
if ( ! $statusStr ) {
return NULL;
} else {
$status = array();
$statusLine = strtok($statusStr,"\n");
while ( $statusLine ) {
list ( $element, $value ) = split(": ",$statusLine);
$status[$element] = $value;
$statusLine = strtok("\n");
// Get the Playlist
$plStr = $this->SendCommand(MPD_CMD_PLLIST);
$this->playlist = $this->_parseFileListResponse($plStr);
$this->playlist_count = count($this->playlist);
// Set Misc Other Variables
$this->state = $status['state'];
if ( ($this->state == MPD_STATE_PLAYING) || ($this->state == MPD_STATE_PAUSED) ) {
$this->current_track_id = $status['song'];
list ($this->current_track_position, $this->current_track_length ) = split(":",$status['time']);
} else {
$this->current_track_id = -1;
$this->current_track_position = -1;
$this->current_track_length = -1;
$this->repeat = $status['repeat'];
$this->random = $status['random'];
$this->db_last_refreshed = $stats['db_update'];
$this->volume = $status['volume'];
$this->uptime = $stats['uptime'];
$this->playtime = $stats['playtime'];
$this->num_songs_played = $stats['songs_played'];
$this->num_artists = $stats['num_artists'];
$this->num_songs = $stats['num_songs'];
$this->num_albums = $stats['num_albums'];
return TRUE;
/* ------------------ DEPRECATED METHODS -------------------*/
/* GetStatistics()
* Retrieves the 'statistics' variables from the server and tosses them into an array.
* NOTE: This function really should not be used. Instead, use $this->[variable]. The function
* will most likely be deprecated in future releases.
function GetStatistics() {
if ( $this->debugging ) echo "mpd->GetStatistics()\n";
$stats = $this->SendCommand(MPD_CMD_STATISTICS);
if ( !$stats ) {
return NULL;
} else {
$statsArray = array();
$statsLine = strtok($stats,"\n");
while ( $statsLine ) {
list ( $element, $value ) = split(": ",$statsLine);
$statsArray[$element] = $value;
$statsLine = strtok("\n");
if ( $this->debugging ) echo "mpd->GetStatistics() / return: " . print_r($statsArray) ."\n";
return $statsArray;
/* GetStatus()
* Retrieves the 'status' variables from the server and tosses them into an array.
* NOTE: This function really should not be used. Instead, use $this->[variable]. The function
* will most likely be deprecated in future releases.
function GetStatus() {
if ( $this->debugging ) echo "mpd->GetStatus()\n";
$status = $this->SendCommand(MPD_CMD_STATUS);
if ( ! $status ) {
return NULL;
} else {
$statusArray = array();
$statusLine = strtok($status,"\n");
while ( $statusLine ) {
list ( $element, $value ) = split(": ",$statusLine);
$statusArray[$element] = $value;
$statusLine = strtok("\n");
if ( $this->debugging ) echo "mpd->GetStatus() / return: " . print_r($statusArray) ."\n";
return $statusArray;
/* GetVolume()
* Retrieves the mixer volume from the server.
* NOTE: This function really should not be used. Instead, use $this->volume. The function
* will most likely be deprecated in future releases.
function GetVolume() {
if ( $this->debugging ) echo "mpd->GetVolume()\n";
$volLine = $this->SendCommand(MPD_CMD_STATUS);
if ( ! $volLine ) {
return NULL;
} else {
list ($vol) = sscanf($volLine,"volume: %d");
if ( $this->debugging ) echo "mpd->GetVolume() / return: $vol\n";
return $vol;
/* GetPlaylist()
* Retrieves the playlist from the server and tosses it into a multidimensional array.
* NOTE: This function really should not be used. Instead, use $this->playlist. The function
* will most likely be deprecated in future releases.
function GetPlaylist() {
if ( $this->debugging ) echo "mpd->GetPlaylist()\n";
$resp = $this->SendCommand(MPD_CMD_PLLIST);
$playlist = $this->_parseFileListResponse($resp);
if ( $this->debugging ) echo "mpd->GetPlaylist() / return ".print_r($playlist)."\n";
return $playlist;
/* ----------------- Command compatibility tables --------------------- */
var $COMPATIBILITY_MIN_TBL = array(
MPD_CMD_SEEK => "0.9.1" ,
MPD_CMD_PLMOVE => "0.9.1" ,
MPD_CMD_RANDOM => "0.9.1" ,
MPD_CMD_PLSWAPTRACK => "0.9.1" ,
MPD_CMD_PLMOVETRACK => "0.9.1" ,
MPD_CMD_PASSWORD => "0.10.0" ,
MPD_CMD_SETVOL => "0.10.0"
var $COMPATIBILITY_MAX_TBL = array(
MPD_CMD_VOLUME => "0.10.0"
} // ---------------------------- end of class ------------------------------
?>
and the HTML output:
<HTML>
<style type="text/css"><!-- .defaultText { font-family: Arial, Helvetica, sans-serif; font-size: 9pt; font-style: normal; font-weight: normal; color: #111111} .err { color: #DD3333 } --></style>
<BODY class="defaultText">
connected == FALSE ) {
echo "Error Connecting: " . $myMpd->errStr;
} else {
switch ($_REQUEST[m]) {
case "add":
if ( is_null($myMpd->PLAdd($_REQUEST[filename])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "rem":
if ( is_null($myMpd->PLRemove($_REQUEST[id])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "setvol":
if ( is_null($myMpd->SetVolume($_REQUEST[vol])) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "play":
if ( is_null($myMpd->Play()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "stop":
if ( is_null($myMpd->Stop()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
case "pause":
if ( is_null($myMpd->Pause()) ) echo "<SPAN CLASS=err>ERROR: " .$myMpd->errStr."</SPAN>";
break;
default:
break;
?>
<DIV ALIGN=CENTER>[ <A HREF="<? echo $_SERVER[PHP_SELF] ?>">Refresh Page</A> ]</DIV>
<HR>
<B>Connected to MPD Version mpd_version ?> at host ?>:port ?></B><BR>
State:
state) {
case MPD_STATE_PLAYING: echo "MPD is Playing [<A HREF='".$_SERVER[PHP_SELF]."?m=pause'>Pause</A>] [<A HREF='".$_SERVER[PHP_SELF]."?m=stop'>Stop</A>]"; break;
case MPD_STATE_PAUSED: echo "MPD is Paused [<A HREF='".$_SERVER[PHP_SELF]."?m=pause'>Unpause</A>]"; break;
case MPD_STATE_STOPPED: echo "MPD is Stopped [<A HREF='".$_SERVER[PHP_SELF]."?m=play'>Play</A>]"; break;
default: echo "(Unknown State!)"; break;
?>
<BR>
Volume: volume ?> [ <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=0'>0</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=25'>25</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=75'>75</A> | <A HREF='<? echo $_SERVER[PHP_SELF] ?>?m=setvol&vol=100'>100</A> ]<BR>
Uptime: uptime) ?><BR>
Playtime: playtime) ?><BR>
state == MPD_STATE_PLAYING or $myMpd->state == MPD_STATE_PAUSED ) { ?>
Currently Playing: playlist[$myMpd->current_track_id]['Artist']." - ".$myMpd->playlist[$myMpd->current_track_id]['Title'] ?><BR>
Track Position: current_track_position."/".$myMpd->current_track_length." (".(round(($myMpd->current_track_position/$myMpd->current_track_length),2)*100)."%)" ?><BR>
Playlist Position: current_track_id+1)."/".$myMpd->playlist_count." (".(round((($myMpd->current_track_id+1)/$myMpd->playlist_count),2)*100)."%)" ?><BR>
<HR>
<B>Playlist - Total: playlist_count ?> tracks (Click to Remove)</B><BR>
playlist) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
foreach ($myMpd->playlist as $id => $entry) {
echo ( $id == $myMpd->current_track_id ? "<B>" : "" ) . ($id+1) . ". <A HREF='".$_SERVER[PHP_SELF]."?m=rem&id=".$id."'>".$entry['Artist']." - ".$entry['Title']."</A>".( $id == $myMpd->current_track_id ? "</B>" : "" )."<BR>\n";
?>
<HR>
<B>Sample Search for the String 'U2' (Click to Add to Playlist)</B><BR>
Search(MPD_SEARCH_ARTIST,'U2');
if ( is_null($sl) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
foreach ($sl as $id => $entry) {
echo ($id+1) . ": <A HREF='".$_SERVER[PHP_SELF]."?m=add&filename=".urlencode($entry['file'])."'>".$entry['Artist']." - ".$entry['Title']."</A><BR>\n";
if ( count($sl) == 0 ) echo "<I>No results returned from search.</I>";
// Example of how you would use Bulk Add features of MPD
// $myarray = array();
// $myarray[0] = "ACDC - Thunderstruck.mp3";
// $myarray[1] = "ACDC - Back In Black.mp3";
// $myarray[2] = "ACDC - Hells Bells.mp3";
// if ( is_null($myMpd->PLAddBulk($myarray)) ) echo "ERROR: ".$myMpd->errStr."\n";
?>
<HR>
<B>Artist List</B><BR>
GetArtists()) ) echo "ERROR: " .$myMpd->errStr."\n";
else {
while(list($key, $value) = each($ar) ) {
echo ($key+1) . ". " . $value . "<BR>";
$myMpd->Disconnect();
// Used to make number of seconds perty.
function secToTimeStr($secs) {
$days = ($secs%604800)/86400;
$hours = (($secs%604800)%86400)/3600;
$minutes = ((($secs%604800)%86400)%3600)/60;
$seconds = (((($secs%604800)%86400)%3600)%60);
if (round($days)) $timestring .= round($days)."d ";
if (round($hours)) $timestring .= round($hours)."h ";
if (round($minutes)) $timestring .= round($minutes)."m";
if (!round($minutes)&&!round($hours)&&!round($days)) $timestring.=" ".round($seconds)."s";
return $timestring;
?>
</BODY></HTML>
As you can see it doesn't seem to understand the pointer operator. Do I have to enable anything in the PHP config files or something?It's set up correctly. Also, it does parse PHP, just not after the arrow.
Here is my php.ini:
; With mbstring support this will automatically be converted into the encoding
; given by corresponding encode setting. When empty mbstring.internal_encoding
; is used. For the decode settings you can distinguish between motorola and
; intel byte order. A decode setting cannot be empty.
; http://php.net/exif.encode-unicode
;exif.encode_unicode = ISO-8859-15
; http://php.net/exif.decode-unicode-motorola
;exif.decode_unicode_motorola = UCS-2BE
; http://php.net/exif.decode-unicode-intel
;exif.decode_unicode_intel = UCS-2LE
; http://php.net/exif.encode-jis
;exif.encode_jis =
; http://php.net/exif.decode-jis-motorola
;exif.decode_jis_motorola = JIS
; http://php.net/exif.decode-jis-intel
;exif.decode_jis_intel = JIS
[Tidy]
; The path to a default tidy configuration file to use when using tidy
; http://php.net/tidy.default-config
;tidy.default_config = /usr/local/lib/php/default.tcfg
; Should tidy clean and repair output automatically?
; WARNING: Do not use this option if you are generating non-html content
; such as dynamic images
; http://php.net/tidy.clean-output
tidy.clean_output = Off
[soap]
; Enables or disables WSDL caching feature.
; http://php.net/soap.wsdl-cache-enabled
soap.wsdl_cache_enabled=1
; Sets the directory name where SOAP extension will put cache files.
; http://php.net/soap.wsdl-cache-dir
soap.wsdl_cache_dir="/tmp"
; (time to live) Sets the number of second while cached file will be used
; instead of original one.
; http://php.net/soap.wsdl-cache-ttl
soap.wsdl_cache_ttl=86400
; Sets the size of the cache limit. (Max. number of WSDL files to cache)
soap.wsdl_cache_limit = 5
[sysvshm]
; A default size of the shared memory segment
;sysvshm.init_mem = 10000
[ldap]
; Sets the maximum number of open links or -1 for unlimited.
ldap.max_links = -1
[mcrypt]
; For more information about mcrypt settings see http://php.net/mcrypt-module-open
; Directory where to load mcrypt algorithms
; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
;mcrypt.algorithms_dir=
; Directory where to load mcrypt modes
; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
;mcrypt.modes_dir=
[dba]
;dba.default_handler=
; Local Variables:
; tab-width: 4
; End:
Last edited by BaconPie (2010-11-04 20:11:33) -
String concatenation is the string manipulation method when you join 2 or more strings together.
In PHP it is a quite easy task. You can use the concatenation operator which is the u2018.u2019 (dot). You can join 2 or more strings into one as follows:
$str1 = 'This';
$str2 = 'is a';
$str3 = 'string';
$full = $str1.' '.$str2.' '.$str3;
echo $full; // This is a string
Besides this you can use the operator to append a string to an existing one like this:
$str = 'Main string';
$str .= ' plus another string';
echo $str; // Main string plus another string
If you concatenate a string with a number, the number will (automatically) be converted into a string value, so the output will be u201Cstringu201D:
$num = 100;
$str = $num.' is a number';
echo $str; // 100 is a number
Trade Show Displays is the retail division of Quality One Engineering.Hi skyvia and Circuitbomb welcome to the php forum.
Thanks for enlightening us with your summary of concatenation which is the most basic function in php and to be honest who care which is faster. If you really care find Sarah Golemon's blog and find the entry on what is happening deep inside php in concatenation. Having said that there are far easier ways to slow down php that do concatenation incorrectly.
You could read from a database for example. That is bound to be an order of magnitude slower than concatenating strings.
PHP is fun for a lot of reasons.
I hope you guys both enjoy SAP and PHP in good measure and contribute the interesting things that you are learning on the forums.
Cheers,
Nigel
Edited by: Nigel James on Oct 28, 2010 12:56 PM -
I am looking to add my date to the beginning of my articles.
Previously, I
was using the string replace function to look for the
begininng of my
paragraph and then place the date in front of that. Bad Jon!
I forgot that
any article with multiple paragraphs would then have multiple
dates.
$artContent = str_replace('<p>', '<p>
'.$artDateEdited.' - ',
$artContent);
So, what I am looking for is how do I do a string replaceon
just the first
paragraph?
TIA,
Jon Parkhurst
PriivaWeb
http://priiva.net.Are you sure there are <p> tags in the data? The only
way that could get
there would be if someone explicitly put them there.
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.dreamweavermx-templates.com
- Template Triage!
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
http://www.macromedia.com/support/search/
- Macromedia (MM) Technotes
==================
"crash" <[email protected]> wrote in message
news:[email protected]...
> LOL, just now getting back to this.
>
> I've got myself in a little bit of a bind, b/c I didn't
foresee my data
> having more than one paragraph.
>
> This is what I'm thinking of doing. If there's a better
way, can somebody
> pipe in?
>
> Take data from database.
> Search for <p> tags, and capture all text within
the first instances
> Limit text to X number of chars
> Replace <p> tags, and my ...Full Story links
>
> Looking now through all of the string functions and
preg_replace right
> now.
>
> Basically, I"m having some problems finding a function
that will replace
> $var on the Xth instance.
>
> Will post tomorrow with my results.
> "Joe Makowiec" <[email protected]> wrote in
message
>
news:[email protected]...
>> On 26 Aug 2006 in macromedia.dreamweaver.appdev,
crash wrote:
>>
>>> I am looking to add my date to the beginning of
my articles.
>>> Previously, I was using the string replace
function to look for the
>>> begininng of my paragraph and then place the
date in front of that.
>>> Bad Jon! I forgot that any article with multiple
paragraphs would
>>> then have multiple dates.
>>>
>>> $artContent = str_replace('<p>',
'<p>
>>> '.$artDateEdited.' - ',
>>> $artContent);
>>>
>>> So, what I am looking for is how do I do a
string replaceon just the
>>> first paragraph?
>>
>>
http://www.php.net/manual/en/function.preg-replace.php
>>
>> In particular, the optional 4th parameter to
preg_replace() is a limit;
>> you can set this to 1.
>>
>> --
>> Joe Makowiec
>>
http://makowiec.net/
>> Email:
http://makowiec.net/email.php
>
> -
Access Denied error with basic XML file operations
Hi,
I'm trying to set up a basic read, write and delete code for XML files which I can build upon in the future. The three methods are bound to three buttons on the page and all three calls are awaited. Here's my code:
Write:
XElement uservarnodes = new XElement("uservars",
new XElement("uservar1", "1"),
new XElement("uservar2", "2"),
new XElement("uservar3", "3"),
new XElement("uservar4", "4"),
new XElement("uservar5", "5"),
new XElement("uservar6", "6"),
new XElement("uservar7", "7"),
new XElement("uservar8", "8"));
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.CreateFileAsync("uservarfile.xml", CreationCollisionOption.ReplaceExisting);
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
using (var outputStream = stream.GetOutputStreamAt(0))
DataWriter mydataWriter = new DataWriter(outputStream);
mydataWriter.WriteString(uservarnodes.ToString());
await mydataWriter.StoreAsync();
await outputStream.FlushAsync();
Read (outputs the data to a textblock):
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.GetFileAsync("uservarfile.xml");
string readtext = await Windows.Storage.FileIO.ReadTextAsync(file);
XElement uservarnodes = XElement.Parse(readtext);
txtTarget.Text = uservarnodes.ToString();
Delete:
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.GetFileAsync("uservarfile.xml");
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
When I tap each of the buttons once it all seems to work. But when I tap any of the buttons again within the same debug session I get an Access denied exception (E_ACCESSDENIED). Other people with this error had to await when calling their method, but I'm
already doing that: private async void btnWrite_Click(object sender, RoutedEventArgs e) { await WriteToXMLFile(); }, etc.
And the intervals between my taps isn't that short that you'd expect that the previously called method still had not finished completing. I don't understand why I'm getting the access denied error.
Related to my question: I have added XML to the File Type Associations, File Open Picker and File Save Picker in the appxmanifest, but somewhere I read that you do not need to do this if you're working with local app data only. Is this true?var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
I think because of your file stream hasn't been closed.
by the way, it can be easier by using System.IO.OpenStreamForWriteAsync extension method
async public static Task<bool> SaveTextFileAsync(string filename, string data)
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
try
using (var s = await file.OpenStreamForWriteAsync())
s.Write(fileBytes, 0, fileBytes.Length);
return true;
catch
return false;
(need using System.IO namespace)
在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。
Maybe you are looking for
-
More Issues with 8.0.1 and 8.0.2 than ever had before
Since updating my iPhone 5S (T-Mobile) to both 8.0.1 and then 8.0.2 I've had more issues than I've ever had with any iOS in the past (with the exception of iPhone 4 running iOS 7, but clearly that is an older phone, not a 1 year old model like the 5S
-
To get text into an Internal table
hi, i need help regarding how to get the text or the header data into an internal table.
-
What are the largest sized memory cards that can be swapped into a macmini 2.6GHz i7 quadcore
What are the largest sized replacement memory cards that can be used in a new macmini 2.6MHz i7 quad core? I see samsung has some 16GB cards and was wondering if the macmini can be jacked up to 32GB instead of the apple store configuration of 2x8GB o
-
Pdf measurements in Metadata panel
Hello, for some reason the measurements of a pdf file are shown incorrectly in the Bridge Metadata panel. It would be a good place to check the size of an ad, but it does not show the measurements right.
-
On my 24" 3.06ghz iMac (4G RAM) I'm having a few issues. The two that are really bugging me are the following, any help deeply appreciated... Dock freezing on right-click. If I right-click dock icons to pull up their menu about 50% percent of the tim