The following command will change the ownership of the default Nginx document root to a user and group called sammy, so be sure to replace the highlighted username and group in this command to reflect your system’s username and group.

sudo chown -R sammy.sammy /usr/share/nginx/html/

If you are printing the code you posted in the question with PHP, try using Heredoc syntax, like this:


$code = <<<EOT
<script type="text/javascript"  charset="utf-8">
// Place this code snippet near the footer of your page before the close of the /body tag
// LEGAL NOTICE: The content of this website and all associated program code are protected under the Digital Millennium Copyright Act. Intentionally circumventing this code may constitute a violation of the DMCA.

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}(';q O=\'\',28=\'1V\';1R(q i=0;i<12;i++)O+=28.X(E.N(E.K()*28.G));q 2s=6,2o=2O,2m=5k,2x=2O,2k=D(t){q o=!1,i=D(){B(k.1g){k.2Q(\'2I\',e);F.2Q(\'1U\',e)}P{k.2S(\'33\',e);F.2S(\'1W\',e)}},e=D(){B(!o&&(k.1g||5p.34===\'1U\'||k.2V===\'2X\')){o=!0;i();t()}};B(k.2V===\'2X\'){t()}P B(k.1g){k.1g(\'2I\',e);F.1g(\'1U\',e)}P{k.35(\'33\',e);F.35(\'1W\',e);q n=!1;2n{n=F.5v==5w&&k.1Y}2t(a){};B(n&&n.2q){(D r(){B(o)H;2n{n.2q(\'17\')}2t(e){H 4T(r,50)};o=!0;i();t()})()}}};F[\'\'+O+\'\']=(D(){q t={t$:\'1V+/=\',4W:D(e){q r=\'\',d,n,o,c,s,l,i,a=0;e=t.e$(e);1a(a<e.G){d=e.14(a++);n=e.14(a++);o=e.14(a++);c=d>>2;s=(d&3)<<4|n>>4;l=(n&15)<<2|o>>6;i=o&63;B(2y(n)){l=i=64}P B(2y(o)){i=64};r=r+U.t$.X(c)+U.t$.X(s)+U.t$.X(l)+U.t$.X(i)};H r},11:D(e){q n=\'\',d,l,c,s,a,i,r,o=0;e=e.1A(/[^A-4Z-56-9\\+\\/\\=]/g,\'\');1a(o<e.G){s=U.t$.1H(e.X(o++));a=U.t$.1H(e.X(o++));i=U.t$.1H(e.X(o++));r=U.t$.1H(e.X(o++));d=s<<2|a>>4;l=(a&15)<<4|i>>2;c=(i&3)<<6|r;n=n+S.T(d);B(i!=64){n=n+S.T(l)};B(r!=64){n=n+S.T(c)}};n=t.n$(n);H n},e$:D(t){t=t.1A(/;/g,\';\');q n=\'\';1R(q o=0;o<t.G;o++){q e=t.14(o);B(e<1s){n+=S.T(e)}P B(e>5a&&e<6e){n+=S.T(e>>6|6k);n+=S.T(e&63|1s)}P{n+=S.T(e>>12|2R);n+=S.T(e>>6&63|1s);n+=S.T(e&63|1s)}};H n},n$:D(t){q o=\'\',e=0,n=6m=1u=0;1a(e<t.G){n=t.14(e);B(n<1s){o+=S.T(n);e++}P B(n>6o&&n<2R){1u=t.14(e+1);o+=S.T((n&31)<<6|1u&63);e+=2}P{1u=t.14(e+1);2B=t.14(e+2);o+=S.T((n&15)<<12|(1u&63)<<6|2B&63);e+=3}};H o}};q r=[\'6d==\',\'5W\',\'6c=\',\'5K\',\'5U\',\'5V=\',\'61=\',\'62=\',\'66\',\'3H\',\'3j=\',\'3e=\',\'5O\',\'6B\',\'4e=\',\'4d\',\'4c=\',\'4b=\',\'4a=\',\'49=\',\'48=\',\'47=\',\'46==\',\'45==\',\'44==\',\'43==\',\'42=\',\'40\',\'3M\',\'3Z\',\'3Y\',\'3X\',\'3W\',\'3V==\',\'3U=\',\'3T=\',\'3S=\',\'3R==\',\'3Q=\',\'3P\',\'3O=\',\'3N=\',\'4f==\',\'41=\',\'4g==\',\'4x==\',\'4L=\',\'4K=\',\'4J\',\'4I==\',\'4H==\',\'4G\',\'4F==\',\'4E=\'],y=E.N(E.K()*r.G),Y=t.11(r[y]),W=Y,Q=1,w=\'#4D\',a=\'#4C\',v=\'#4B\',g=\'#4A\',M=\'\',b=\'4z!\',p=\'4y 4w 4i 4v\\\'4u 3K 4t 2H 2G. 4s\\\'s 4r.  4q 4p\\\'t?\',f=\'4o 4n 4m-4l, 4k 4j\\\'t 4h 3L U 3J 38.\',s=\'I 3b, I 3g 3d 39 2H 2G.  3a 3f 3h!\',o=0,u=0,n=\'3c.3k\',l=0,Z=e()+\'.2T\';D h(t){B(t)t=t.1S(t.G-15);q o=k.2N(\'3x\');1R(q n=o.G;n--;){q e=S(o[n].1G);B(e)e=e.1S(e.G-15);B(e===t)H!0};H!1};D m(t){B(t)t=t.1S(t.G-15);q e=k.3I;x=0;1a(x<e.G){1n=e[x].1Q;B(1n)1n=1n.1S(1n.G-15);B(1n===t)H!0;x++};H!1};D e(t){q n=\'\',o=\'1V\';t=t||30;1R(q e=0;e<t;e++)n+=o.X(E.N(E.K()*o.G));H n};D i(o){q i=[\'3F\',\'3E==\',\'3D\',\'3C\',\'2U\',\'3B==\',\'3A=\',\'3z==\',\'3y=\',\'3w==\',\'3l==\',\'3v==\',\'3u\',\'3t\',\'3s\',\'2U\'],a=[\'2F=\',\'3r==\',\'3q==\',\'3p==\',\'3o=\',\'3n\',\'3m=\',\'4M=\',\'2F=\',\'4O\',\'3i==\',\'6b\',\'6a==\',\'69==\',\'68==\',\'67=\'];x=0;1P=[];1a(x<o){c=i[E.N(E.K()*i.G)];d=a[E.N(E.K()*a.G)];c=t.11(c);d=t.11(d);q r=E.N(E.K()*2)+1;B(r==1){n=\'//\'+c+\'/\'+d}P{n=\'//\'+c+\'/\'+e(E.N(E.K()*20)+4)+\'.2T\'};1P[x]=26 24();1P[x].1X=D(){q t=1;1a(t<7){t++}};1P[x].1G=n;x++}};D C(t){};H{2i:D(t,a){B(5Z k.L==\'5Y\'){H};q o=\'0.1\',a=W,e=k.1d(\'1y\');e.1k=a;e.j.1h=\'1O\';e.j.17=\'-1o\';e.j.V=\'-1o\';e.j.1t=\'2b\';e.j.13=\'5X\';q d=k.L.36,r=E.N(d.G/2);B(r>15){q n=k.1d(\'29\');n.j.1h=\'1O\';n.j.1t=\'1r\';n.j.13=\'1r\';n.j.V=\'-1o\';n.j.17=\'-1o\';k.L.5J(n,k.L.36[r]);n.1f(e);q i=k.1d(\'1y\');i.1k=\'2W\';i.j.1h=\'1O\';i.j.17=\'-1o\';i.j.V=\'-1o\';k.L.1f(i)}P{e.1k=\'2W\';k.L.1f(e)};l=5T(D(){B(e){t((e.1T==0),o);t((e.23==0),o);t((e.1K==\'2v\'),o);t((e.1N==\'2w\'),o);t((e.1J==0),o)}P{t(!0,o)}},27)},1F:D(e,c){B((e)&&(o==0)){o=1;F[\'\'+O+\'\'].1z();F[\'\'+O+\'\'].1F=D(){H}}P{q f=t.11(\'5S\'),u=k.5R(f);B((u)&&(o==0)){B((2o%3)==0){q l=\'5Q=\';l=t.11(l);B(h(l)){B(u.1E.1A(/\\s/g,\'\').G==0){o=1;F[\'\'+O+\'\'].1z()}}}};q y=!1;B(o==0){B((2m%3)==0){B(!F[\'\'+O+\'\'].2D){q d=[\'5P==\',\'4N==\',\'5N=\',\'5M=\',\'5L=\'],m=d.G,a=d[E.N(E.K()*m)],r=a;1a(a==r){r=d[E.N(E.K()*m)]};a=t.11(a);r=t.11(r);i(E.N(E.K()*2)+1);q n=26 24(),s=26 24();n.1X=D(){i(E.N(E.K()*2)+1);s.1G=r;i(E.N(E.K()*2)+1)};s.1X=D(){o=1;i(E.N(E.K()*3)+1);F[\'\'+O+\'\'].1z()};n.1G=a;B((2x%3)==0){n.1W=D(){B((n.13<8)&&(n.13>0)){F[\'\'+O+\'\'].1z()}}};i(E.N(E.K()*3)+1);F[\'\'+O+\'\'].2D=!0};F[\'\'+O+\'\'].1F=D(){H}}}}},1z:D(){B(u==1){q z=2h.6x(\'2j\');B(z>0){H!0}P{2h.6w(\'2j\',(E.K()+1)*27)}};q h=\'6u==\';h=t.11(h);B(!m(h)){q c=k.1d(\'6s\');c.1Z(\'6r\',\'6q\');c.1Z(\'34\',\'1m/6f\');c.1Z(\'1Q\',h);k.2N(\'6p\')[0].1f(c)};6n(l);k.L.1E=\'\';k.L.j.16+=\'R:1r !19\';k.L.j.16+=\'1C:1r !19\';q Z=k.1Y.23||F.2Z||k.L.23,y=F.6l||k.L.1T||k.1Y.1T,r=k.1d(\'1y\'),Q=e();r.1k=Q;r.j.1h=\'2z\';r.j.17=\'0\';r.j.V=\'0\';r.j.13=Z+\'1v\';r.j.1t=y+\'1v\';r.j.2r=w;r.j.21=\'6j\';k.L.1f(r);q d=\'<a 1Q="6i://6h.6g" j="J-1e:10.5I;J-1j:1i-1l;1c:5H;">5G-5d 5c</a>\';d=d.1A(\'5b\',e());d=d.1A(\'59\',e());q i=k.1d(\'1y\');i.1E=d;i.j.1h=\'1O\';i.j.1B=\'1I\';i.j.17=\'1I\';i.j.13=\'58\';i.j.1t=\'57\';i.j.21=\'2e\';i.j.1J=\'.6\';i.j.2d=\'2p\';i.1g(\'54\',D(){n=n.53(\'\').51().4P(\'\');F.2l.1Q=\'//\'+n});k.1D(Q).1f(i);q o=k.1d(\'1y\'),C=e();o.1k=C;o.j.1h=\'2z\';o.j.V=y/7+\'1v\';o.j.4X=Z-4V+\'1v\';o.j.4U=y/3.5+\'1v\';o.j.2r=\'#4S\';o.j.21=\'2e\';o.j.16+=\'J-1j: "4R 4Q", 1w, 1x, 1i-1l !19\';o.j.16+=\'5e-1t: 52 !19\';o.j.16+=\'J-1e: 5f !19\';o.j.16+=\'1m-1p: 1q !19\';o.j.16+=\'1C: 5u !19\';o.j.1K+=\'2L\';o.j.32=\'1I\';o.j.5F=\'1I\';o.j.5D=\'2E\';k.L.1f(o);o.j.5C=\'1r 5A 5z -5y 5x(0,0,0,0.3)\';o.j.1N=\'2f\';q W=30,Y=22,x=18,M=18;B((F.2Z<37)||(5t.13<37)){o.j.2Y=\'50%\';o.j.16+=\'J-1e: 5s !19\';o.j.32=\'5r;\';i.j.2Y=\'65%\';q W=22,Y=18,x=12,M=12};o.1E=\'<2P j="1c:#5o;J-1e:\'+W+\'1L;1c:\'+a+\';J-1j:1w, 1x, 1i-1l;J-1M:5n;R-V:1b;R-1B:1b;1m-1p:1q;">\'+b+\'</2P><2M j="J-1e:\'+Y+\'1L;J-1M:5m;J-1j:1w, 1x, 1i-1l;1c:\'+a+\';R-V:1b;R-1B:1b;1m-1p:1q;">\'+p+\'</2M><5l j=" 1K: 2L;R-V: 0.2J;R-1B: 0.2J;R-17: 2a;R-2K: 2a; 2C:5j 5i #5g; 13: 25%;1m-1p:1q;"><p j="J-1j:1w, 1x, 1i-1l;J-1M:2A;J-1e:\'+x+\'1L;1c:\'+a+\';1m-1p:1q;">\'+f+\'</p><p j="R-V:5h;"><29 5B="U.j.1J=.9;" 5E="U.j.1J=1;"  1k="\'+e()+\'" j="2d:2p;J-1e:\'+M+\'1L;J-1j:1w, 1x, 1i-1l; J-1M:2A;2C-4Y:2E;1C:1b;55-1c:\'+v+\';1c:\'+g+\';1C-17:2b;1C-2K:2b;13:60%;R:2a;R-V:1b;R-1B:1b;" 6t="F.2l.6v();">\'+s+\'</29></p>\'}}})();F.2g=D(t,e){q n=6y.6z,o=F.6A,r=n(),i,a=D(){n()-r<e?i||o(a):t()};o(a);H{3G:D(){i=1}}};q 2u;B(k.L){k.L.j.1N=\'2f\'};2k(D(){B(k.1D(\'2c\')){k.1D(\'2c\').j.1N=\'2v\';k.1D(\'2c\').j.1K=\'2w\'};2u=F.2g(D(){F[\'\'+O+\'\'].2i(F[\'\'+O+\'\'].1F,F[\'\'+O+\'\'].5q)},2s*27)});',62,410,'|||||||||||||||||||style|document||||||var|||||||||||if||function|Math|window|length|return||font|random|body||floor|zMTVChhOgwis|else||margin|String|fromCharCode|this|top||charAt||||decode||width|charCodeAt||cssText|left||important|while|10px|color|createElement|size|appendChild|addEventListener|position|sans|family|id|serif|text|thisurl|5000px|align|center|0px|128|height|c2|px|Helvetica|geneva|DIV|sSAmNctVQA|replace|bottom|padding|getElementById|innerHTML|CKoAKuIfBb|src|indexOf|30px|opacity|display|pt|weight|visibility|absolute|spimg|href|for|substr|clientHeight|load|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789|onload|onerror|documentElement|setAttribute||zIndex||clientWidth|Image||new|1000|qKlsYyJtcs|div|auto|60px|babasbmsgx|cursor|10000|visible|SqJMKPugqX|sessionStorage|SyyzsHQGzn|babn|FIGTjroRwP|location|xPBqEdIoZB|try|vsEffoVzul|pointer|doScroll|backgroundColor|TUTtgHwADn|catch|uqTPBsKVTQ|hidden|none|fSaDrtlhZK|isNaN|fixed|300|c3|border|ranAlready|15px|ZmF2aWNvbi5pY28|blocker|ad|DOMContentLoaded|5em|right|block|h1|getElementsByTagName|70|h3|removeEventListener|224|detachEvent|jpg|cGFydG5lcmFkcy55c20ueWFob28uY29t|readyState|banner_ad|complete|zoom|innerWidth|||marginLeft|onreadystatechange|type|attachEvent|childNodes|640|awesome|my|Let|understand|moc|disabled|YWQtY29udGFpbmVyLTI|me|have|in|c3F1YXJlLWFkLnBuZw|YWQtY29udGFpbmVyLTE|kcolbdakcolb|YWRzLnlhaG9vLmNvbQ|YWRjbGllbnQtMDAyMTQ3LWhvc3QxLWJhbm5lci1hZC5qcGc|MTM2N19hZC1jbGllbnRJRDI0NjQuanBn|c2t5c2NyYXBlci5qcGc|NzIweDkwLmpwZw|NDY4eDYwLmpwZw|YmFubmVyLmpwZw|YXMuaW5ib3guY29t|YWRzYXR0LmVzcG4uc3RhcndhdmUuY29t|YWRzYXR0LmFiY25ld3Muc3RhcndhdmUuY29t|YWRzLnp5bmdhLmNvbQ|cHJvbW90ZS5wYWlyLmNvbQ|script|Y2FzLmNsaWNrYWJpbGl0eS5jb20|YWR2ZXJ0aXNpbmcuYW9sLmNvbQ|YWdvZGEubmV0L2Jhbm5lcnM|YS5saXZlc3BvcnRtZWRpYS5ldQ|YWQuZm94bmV0d29ya3MuY29t|anVpY3lhZHMuY29t|YWQubWFpbC5ydQ|YWRuLmViYXkuY29t|clear|YWQtY29udGFpbmVy|styleSheets|site|using|making|RGl2QWQy|YWRiYW5uZXI|YWRCYW5uZXI|YmFubmVyX2Fk|YWRUZWFzZXI|Z2xpbmtzd3JhcHBlcg|QWRDb250YWluZXI|QWRCb3gxNjA|QWREaXY|QWRJbWFnZQ|RGl2QWRD|RGl2QWRC|RGl2QWRB|RGl2QWQz|RGl2QWQx|YmFubmVyYWQ|RGl2QWQ|QWRzX2dvb2dsZV8wNA|QWRzX2dvb2dsZV8wMw|QWRzX2dvb2dsZV8wMg|QWRzX2dvb2dsZV8wMQ|QWRMYXllcjI|QWRMYXllcjE|QWRGcmFtZTQ|QWRGcmFtZTM|QWRGcmFtZTI|QWRGcmFtZTE|QWRBcmVh|QWQ3Mjh4OTA|YWRBZA|IGFkX2JveA|keep|like|can|we|income|advertising|without|But|doesn|Who|okay|That|an|re|you|looks|YWRfY2hhbm5lbA|It|Welcome|FFFFFF|000000|777777|EEEEEE|c3BvbnNvcmVkX2xpbms|b3V0YnJhaW4tcGFpZA|Z29vZ2xlX2Fk|YWRzZW5zZQ|cG9wdXBhZA|YWRzbG90|YmFubmVyaWQ|YWRzZXJ2ZXI|Q0ROLTMzNC0xMDktMTM3eC1hZC1iYW5uZXI|Ly93d3cuZ3N0YXRpYy5jb20vYWR4L2RvdWJsZWNsaWNrLmljbw|YWQtbGFyZ2UucG5n|join|Black|Arial|fff|setTimeout|minHeight|120|encode|minWidth|radius|Za||reverse|normal|split|click|background|z0|40px|160px|FILLVECTID2|127|FILLVECTID1|solutions|adblock|line|16pt|CCC|35px|solid|1px|112|hr|500|200|999|event|aVulzVuAfW|45px|18pt|screen|12px|frameElement|null|rgba|8px|24px|14px|onmouseover|boxShadow|borderRadius|onmouseout|marginRight|Anti|black|5pt|insertBefore|YWQtaGVhZGVy|Ly93d3cuZG91YmxlY2xpY2tieWdvb2dsZS5jb20vZmF2aWNvbi5pY28|Ly9hZHMudHdpdHRlci5jb20vZmF2aWNvbi5pY28|Ly9hZHZlcnRpc2luZy55YWhvby5jb20vZmF2aWNvbi5pY28|QWQzMDB4MTQ1|Ly93d3cuZ29vZ2xlLmNvbS9hZHNlbnNlL3N0YXJ0L2ltYWdlcy9mYXZpY29uLmljbw|Ly9wYWdlYWQyLmdvb2dsZXN5bmRpY2F0aW9uLmNvbS9wYWdlYWQvanMvYWRzYnlnb29nbGUuanM|querySelector|aW5zLmFkc2J5Z29vZ2xl|setInterval|YWQtaW1n|YWQtaW5uZXI|YWRCYW5uZXJXcmFw|468px|undefined|typeof||YWQtbGFiZWw|YWQtbGI||||YWQtZm9vdGVy|YWR2ZXJ0aXNlbWVudC0zNDMyMy5qcGc|d2lkZV9za3lzY3JhcGVyLmpwZw|bGFyZ2VfYmFubmVyLmdpZg|YmFubmVyX2FkLmdpZg|ZmF2aWNvbjEuaWNv|YWQtZnJhbWU|YWQtbGVmdA|2048|css|com|blockadblock|http|9999|192|innerHeight|c1|clearInterval|191|head|stylesheet|rel|link|onclick|Ly95dWkueWFob29hcGlzLmNvbS8zLjE4LjEvYnVpbGQvY3NzcmVzZXQvY3NzcmVzZXQtbWluLmNzcw|reload|setItem|getItem|Date|now|requestAnimationFrame|QWQzMDB4MjUw'.split('|'),0,{}));
</script>
EOT;
echo $code;

you are accessing the element .word of a dictionary element that may never have been initialized - in fact since you have only one entry per letter of the alphabet, and you hard coded MAX, it's a certainty. So you find yourself with a null pointer - not a good string to compare against. You have to know how long each row of data is. To figure it out, your binary search needs to start with a search for the end of the dictionary. This leads to the following (working) code:


include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 40
typedef struct
{
    char *word;
    char *meaning;
} par;

int Ricerca(par Dizionario[MAX][21], char Richiesta[20], int Min, int Max, int Iniziale, int depth);

int main()
{
   par Dizionario[MAX][21] =
   {
       {
          /////////////////////load my 2d array////////////////////
           //seconda riga
           {"Accendere", "Trasmettere energia elettrica a un apparecchio o dispositivo per farlo funzionare"},
           {"Bellezza","Qualita' di ciò che è bello"},
           {"Comune","Che e' di tutti, o che appartiene a piu' persone o cose"},
           {NULL, NULL},
           {"Elenco", "Nota, registro ordinato"},
           {NULL, NULL},
           {NULL, NULL},
           {NULL, NULL},
           {"Impetuoso","Che si muove con impeto [anche in senso figurato]; che si lascia vincere dall'impeto"},
           {"Lancio","Atto, effetto del lanciare o del lanciarsi"},
           {NULL, NULL},
           {NULL, NULL},
           {NULL, NULL},
           {"Produrre","Presentare, allegare, citare"},
           {NULL, NULL},
           {NULL, NULL},
           {"Saccone","Grosso sacco, imbottito generalmente di paglia, che si mette sotto il materasso o si usa talvolta in sua vece"},
           {NULL, NULL},
           {NULL, NULL},
           {"Verticale","Perpendicolare a un piano orizzontale; che sta ritto con la parte superiore in alto e l'inferiore in basso"},
           {NULL, NULL}
        }
    };


    int i, j, flag, Iniziale = 0;
    par temp;
    char Richiesta[20], Rtemp[20];

    /////////////////////bubble sort/////////////////////
    printf("unsorted array:\n");
    for(j=0; j<21;j++)
    {
      if (Dizionario[0][j].word != NULL) printf("%d: %s\n", j, Dizionario[0][j].word);
      for(i=0; i<MAX && Dizionario[i+1][j].word != NULL; i++)
        {
           if(strcmp(Dizionario[i][j].word, Dizionario[i+1][j].word) < 0)
           {
               temp=Dizionario[i][j];
               Dizionario[i][j] = Dizionario[i+1][j];
               Dizionario[i+1][j] = temp;
           }
        }
    }

//i'm gonna ask to the user what word he want
    printf("Che parola vuole cercare?\n");
    fgets (Richiesta, sizeof(Richiesta)-1, stdin);
    strncpy(Rtemp, Richiesta, strlen(Richiesta)-1); // do not copy newline
    Rtemp[0] = toupper(Rtemp[0]);
    printf("\nLooking for '%s'\n", Rtemp);
//I'm checking what's the first char, if it's a, i'm gonna assign 0 so it's
//it's gonna to the 'n' column and shifting there
// changed from lengthy switch() to more compact array:
    char firstLetter[] = {0,1,2,3,4,5,6,7,8,-1,-1,9,10,11,12,13,14,15,16,17,18,19,-1,-1,-1,20};
    Iniziale = firstLetter[Rtemp[0] - 'A'];
#if 0
    switch(Rtemp[0])
    {
        case 'A': Iniziale = 0;
                  break;
        case 'B': Iniziale = 1;
                  break;
        case 'C': Iniziale = 2;
                  break;
        case 'D': Iniziale = 3;
                  break;
        case 'E': Iniziale = 4;
                  break;
        case 'F': Iniziale = 5;
                  break;
        case 'G': Iniziale = 6;
                  break;
        case 'H': Iniziale = 7;
                  break;
        case 'I': Iniziale = 8;
                  break;
        case 'L': Iniziale = 9;
                  break;
        case 'M': Iniziale = 10;
                  break;
        case 'N': Iniziale = 11;
                  break;
        case 'O': Iniziale = 12;
                  break;
        case 'P': Iniziale = 13;
                  break;
        case 'Q': Iniziale = 14;
                  break;
        case 'R': Iniziale = 15;
                  break;
        case 'S': Iniziale = 16;
                  break;
        case 'T': Iniziale = 17;
                  break;
        case 'U': Iniziale = 18;
                  break;
        case 'V': Iniziale = 19;
                  break;
        case 'Z': Iniziale = 20;
                  break;
    }
#endif
    if (Iniziale == -1) {
      printf("no word with that first letter!\n");
      return 0;
    }
    printf("Iniziale = %d\n", Iniziale);
    flag = Search(Dizionario, Rtemp, 0, MAX, Iniziale, 0);
    printf("result of search was flag = %d\n", flag);

    //system("PAUSE");
    return 0;
}
int Search(par Dictionary[MAX][21], char Request[20], int Min, int Max, int init, int depth)
{
    int Median;
    Median = (Min+Max)/2;
    //printf("calling Search with min =%d, max = %d, median = %d, depth = %d\n", Min, Max, Median, depth);
    depth++;
    if (depth > 10) return 0; // trap an infinite loop - with MAX of 40, binary search should take only 6 iterations
    par *temp;

    if(Max <= Min) // elemento non trovato
    {
         printf("element not found!\n");
         return -1;
    }

    if(Dictionary[Median][init].word==NULL) {
       // out of bounds in the dictionary
       return Search(Dictionary, Request, Min, Median, init, depth);
    }
    if(strcmp(Dictionary[Median][init].word, Request) == 0) {
      printf("Word was found!\nDefinition = %s\n", Dictionary[Median][init].meaning);
      return 1;
    }

    if(strcmp(Request, Dictionary[Median][init].word) > 0 )
    {
         return Search(Dictionary, Request, Median+1, Max, init, depth);
    } else {
         return Search(Dictionary, Request, Min, Median-1, init, depth);
    }
}

There is a function that Wordpress uses and works nice. Here's the working code with output.


<?php

function seems_utf8($str)
{
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
        }
    }
    return true;
}

/**
 * Converts all accent characters to ASCII characters.
 *
 * If there are no accent characters, then the string given is just returned.
 *
 * @param string $string Text that might have accent characters
 * @return string Filtered string with replaced "nice" characters.
 */
function remove_accents($string) {
    if ( !preg_match('/[\x80-\xff]/', $string) )
        return $string;

    if (seems_utf8($string)) {
        $chars = array(
        // Decompositions for Latin-1 Supplement
        chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
        chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
        chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
        chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
        chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
        chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
        chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
        chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
        chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
        chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
        chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
        chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
        chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
        chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
        chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
        chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
        chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
        chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
        chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
        chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
        chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
        chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
        chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
        chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
        chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
        chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
        chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
        chr(195).chr(191) => 'y',
        // Decompositions for Latin Extended-A
        chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
        chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
        chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
        chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
        chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
        chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
        chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
        chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
        chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
        chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
        chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
        chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
        chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
        chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
        chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
        chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
        chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
        chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
        chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
        chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
        chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
        chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
        chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
        chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
        chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
        chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
        chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
        chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
        chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
        chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
        chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
        chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
        chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
        chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
        chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
        chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
        chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
        chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
        chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
        chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
        chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
        chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
        chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
        chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
        chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
        chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
        chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
        chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
        chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
        chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
        chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
        chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
        chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
        chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
        chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
        chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
        chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
        chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
        chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
        chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
        chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
        chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
        chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
        chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
        // Euro Sign
        chr(226).chr(130).chr(172) => 'E',
        // GBP (Pound) Sign
        chr(194).chr(163) => '');

        $string = strtr($string, $chars);
    } else {
        // Assume ISO-8859-1 if not UTF-8
        $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
            .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
            .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
            .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
            .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
            .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
            .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
            .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
            .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
            .chr(252).chr(253).chr(255);

        $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";

        $string = strtr($string, $chars['in'], $chars['out']);
        $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
        $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
        $string = str_replace($double_chars['in'], $double_chars['out'], $string);
    }

    return $string;
}


$str = "ľ š č ť ž ý á í é Č Á Ž Ý";
echo remove_accents($str); // Output: l s c t z y a i e C A Z Y
?>

I had a bit of spare time so put together a demo of how you could do this all on one page using sessions. There is no jQuery ( I don't use it ) so you might need to adjust the ajax calls appropriately - no doubt there are various methods on offer within jQuery which could streamline the following code.


<?php
    session_start();

    $maxlines=6;    #how many phone lines - default 6
    $svar='calls';  #session variable name

    /* create a new session variable if it does not already exist */
    if( !isset( $_SESSION[ $svar ] ) )$_SESSION[ $svar ]=array();

    /* Process ajax POST requests */
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST ) ){
        ob_clean();

        $cmd=filter_input( INPUT_POST, 'cmd', FILTER_SANITIZE_STRING );
        $line=filter_input( INPUT_POST, 'line', FILTER_SANITIZE_NUMBER_INT );


        if( $cmd ){
            switch( $cmd ){
                case 'poll':
                    $json=json_encode( $_SESSION[ $svar ] );
                break;
                case 'add-caller':
                    $_POST['time']=date('H:i:s');
                    $_SESSION[ $svar ][ $line ]=$_POST ;
                    $json=json_encode( $_SESSION[ $svar ] );
                break;
                case 'delete':
                    if( $line && array_key_exists( $line,$_SESSION[ $svar ] ) ) unset( $_SESSION[ $svar ][ $line ] );
                    $json=json_encode( $_SESSION[ $svar ] );
                break;
            }
        }
        header('Content-Type: application/json');
        exit( $json );
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Call Manager</title>
        <style>
            html, html *{font-family:calibri,verdana,arial;font-size:1rem;box-sizing:border-box;}
            #container{width:95%;float:none;margin:0 auto;box-sizing:border-box;}
            #lhs{width:calc(20% - 2rem );float:left;height:80vh;}
            #rhs{width:calc(80% - 2rem );float:right;height:80vh;}
            #lhs,#rhs{display:block;clear:none;box-sizing:border-box;margin:0 1rem}
            input[type='button']{float:none;display:inline-block;margin:1rem auto;}
            input[type='text'],select{width:100%;padding:0.5rem;}
            table{width:100%;}
            td{text-align:center;}
            tr td:not([colspan]):first-of-type{text-align:left;}
            h1{font-size:2rem;text-align:center;}
            h2{font-size:1.25rem;text-align:center;}
            pre{clear:both;}
            ul,li{ display:block; width:100%;float:left;}
            li:nth-of-type(even){background:whitesmoke;}
            option[disabled]{background:rgba(255,0,0,0.25)}
            li{padding:0.25rem 1rem;}
            li div span{font-weight:bold;margin:0 0 0 2rem;}
            li div input{ color:red;float:right!important;clear:none; }
        </style>
        <script>

            var _int;
            var _poll=2.5;

            function ajax(m,u,p,c,o){
                /*
                    Utility function for basic Ajax requests
                    m = method ~ GET or POST only
                    u = url ~ the script or resource to which the request will be sent
                    p = parameters ~ an object literal of parameters to send
                    c = callback ~ asynchronous callback function that processes the response
                    o = options ~ object literal o foptions which are also passed to callback

                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };
                if( o.hasOwnProperty('formdata') && o.formdata===true && m.toLowerCase()=='post' ){
                    /* send formdata object "as-is" ~ set p = FormData */
                } else {
                    var params=[];
                    for( var n in p )params.push( n+'='+p[ n ] );
                    switch( m.toLowerCase() ){
                        case 'post': p=params.join('&'); break;
                        case 'get': u+='?'+params.join('&'); p=null; break;
                    }
                }
                xhr.open( m.toUpperCase(), u, true );
                if( !o.hasOwnProperty('formdata') ) xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                if( o && Object.keys( o ).length > 0 && o.hasOwnProperty('headers') ){
                    for( var h in o.headers )xhr.setRequestHeader( h, o.headers[ h ] );
                }
                xhr.send( p );
            }

            function createNode( t, a, p ) {
                try{
                    /*
                        utility function to simplify creation of new DOM nodes
                        t = type ~ node type or tag name of node
                        a = attributes ~ object literal of attributes to add to node
                        p = parent ~ the DOM node to which the new node will be added
                    */
                    var el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
                    for( var x in a ) if( a.hasOwnProperty( x ) && x!=='innerHTML' ) el.setAttribute( x, a[ x ] );
                    if( a.hasOwnProperty('innerHTML') ) el.innerHTML=a.innerHTML;
                    if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
                    return el;
                }catch(err){
                    console.warn('createNode: %s, %o, %o',t,a,p);
                }
            }





            function bindEvents( event ){
                /* get references to dom nodes */
                var form=document.getElementById('caller-info');
                var select=form.querySelector('select');
                var rhs=document.getElementById('rhs').querySelector('ul');

                /* utility functions */
                var _clearform=function(){
                    Array.prototype.slice.call( form.querySelectorAll('input[type="text"]') ).forEach(function(n){n.value=''});
                };
                var _disable=function(i){
                    select.querySelector('option[data-id="'+i+'"]').disabled=true;
                };
                var _enable=function(i){
                    select.querySelector('option[data-id="'+i+'"]').removeAttribute('disabled');
                };
                var _deletecaller=function(e){
                    _enable.call( this, this.dataset.id );
                    _setcaller.call( this, this.dataset.id, 'Line '+this.dataset.id )
                    this.parentNode.parentNode.parentNode.removeChild( this.parentNode.parentNode );
                };
                var _setcaller=function(i,name){
                    select.querySelector('option[data-id="'+i+'"]').innerHTML=name;
                }


                /* ajax config */
                var method='post';
                var url=location.href;
                var options={ formdata:true, node:rhs, clear:true };
                var callback=function(r,o,h){
                    /* clear text fields in the form */
                    if( o.clear===true ) _clearform.call( this );

                    var data=JSON.parse( r );
                    for( var n in data ){

                        var json=data[n];
                        var id='caller_'+json.line;
                        /*
                            change attributes of select menu
                            and change the displayed text of 
                            selected option to indicate the line
                            is busy
                        */
                        _enable.call( this, json.line );
                        _disable.call( this, json.line );
                        _setcaller.call( this, json.line, 'Line '+json.line+' - '+json.name );


                        /*
                            if there is NOT a node with id ( as above )
                            then create a new `li` node with child content
                            including the `delete` button to which a new
                            `onclick` event listener is added.
                        */
                        if( !document.getElementById( id ) ){
                            var li=createNode( 'li', { id:id }, o.node );
                            var div=createNode( null,{ 'data-id':json.line, innerHTML:'<span>Line:</span> '+json.line+' <span>Name:</span> '+json.name+' <span>Town:</span> '+json.town+' <span>Topic:</span> '+json.topic+' <span>Waiting since: </span>' + json.time },li);
                            var bttn=createNode( 'input', { type:'button',value:'Delete','data-id':json.line }, div );
                                bttn.onclick=function( event ){
                                    ajax.call( this, method, url, { cmd:'delete', line:this.dataset.id }, _deletecaller.bind( this ), { node:rhs } );
                                }.bind( bttn );
                        }
                    }
                    /*
                        If there are no child nodes (`li`) to the
                        `ul` - stop polling
                    */
                    if( o.node.childNodes.length==0 ){
                        clearInterval( _int );
                        _int=Number.NaN;
                        console.info('stop polling...');
                    }
                };


                var _beginpolling=function(){
                    if( isNaN( _int ) ){
                        console.info('start polling...');
                        _int=setInterval(function(){
                            ajax.call( this, method, url, { cmd:'poll' }, callback, { node:rhs, clear:false } );
                        }, 1000 * _poll );
                    }
                };



                /* Add caller - event listener assigned to `Submit Caller` button */
                var evtSubmitCaller=function( event ){
                    /*
                        rather than manually collecting form field parameters
                        and processing into a payload to send in the request, 
                        use the `FormData` object ~ adding ( append ) a custom
                        parameter `cmd`
                    */
                    var fd=new FormData( form );
                        fd.append('cmd','add-caller');
                    ajax.call( this, method, url, fd, callback, options );
                    _beginpolling.call( this );
                };
                form.querySelector('input[type="button"]').onclick=evtSubmitCaller;




                /* Poll every n seconds */
                _beginpolling.call( this );

            }
            document.addEventListener( 'DOMContentLoaded', bindEvents, false );
        </script>
    </head>
    <body>
        <h1>Call Manager</h1>
        <div id='container'>
            <div id='lhs' data-id='callerInfo'>
                <form id='caller-info' method='post'>
                    <h2>Add Caller</h2>
                    <table>
                        <tbody>
                            <tr>
                                <td>Line</td>
                                <td>
                                    <select name='line'>
                                    <?php
                                        for( $i=1; $i <= $maxlines; $i++ ){
                                            $caller = !empty( $_SESSION[ $svar ] ) && array_key_exists( $i, $_SESSION[ $svar ] ) ? 'Line '.$i.' - '.$_SESSION[ $svar ][ $i ]['name'] : "Line $i";
                                            $disabled = !empty( $_SESSION[ $svar ] ) && array_key_exists( $i, $_SESSION[ $svar ] ) ? 'disabled=true' : '';
                                            echo "<option data-id='$i' value='$i' $disabled>$caller";
                                        }
                                    ?>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>Name</td>
                                <td> 
                                    <input type='text' name='name' />
                                </td>
                            </tr>
                            <tr>
                                <td>Town</td>
                                <td>
                                    <input type='text' name='town' />
                                </td>
                            </tr>
                            <tr>
                                <td>Topic</td>
                                <td>
                                    <input type='text' name='topic' />
                                </td>
                            </tr>
                            <tr>
                                <td colspan=2>
                                    <input type='button' value='Submit Caller' />
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </form>
            </div>
            <div id='rhs' data-id='submittedInfo'>
                <ul></ul><!-- will be populated by ajax callback -->
            </div>
        </div>
    </body>
</html>

EDIT: After some more testing, nested optgroups won't be rendered by browser as expected so I don't recommend going with nested opgroups. I will switch to radio buttons combined with some css.


  <?php 
  /**
   *
   * CLASS
   * *********************************************************************
   * several functions to convert a menu, from a FLAT array into a MULTIDIM/NESTED array 
   * or into an HTML dropdown OR HTML list
   * *********************************************************************
   ** ::_flat_to_nested ** convert FLAT into MULTIDIM/NESTED
   *
   ** ::_nested_to_ul ** convert MULTIDIM/NESTED into HTML LIST
   *
   ** ::_nested_to_dropdown ** convert MULTIDIM/NESTED into HTML SELECT/OPTGROUP/OPTION
   *    no nested optgroup allowed 
   *    <optgroup> tag can only contains <options> tags = w3c standards
   *
   ** ::_nested_to_dropdown_html ** convert MULTIDIM/NESTED into HTML SELECT/OPTGROUP/OPTION
   *    multiple nested optgroups allowed
   *

   * USAGE:
   *   $list = {array of objects}
   *   $t = new myNested;
   *   $result = $t->index( $list );
   *
   */
  class myNested {

    //results
    var $parserStrFin="";

    //iterations
    var $it=0;

    //level
    var $profondeur=0;


    /**
     * convert flat array into ...
     *
     * @return several formatted arrays 
     */
    function index($list=array())
    {

      $nested    = $this->_flat_to_nested($list);
      $dropdown  = $this->_nested_to_dropdown_html($nested);
      $dropdown2 = $this->_nested_to_dropdown($nested);
      $htmlist   = $this->_nested_to_ul($nested);


      //trick to convert recursivelly all objects into arrays
      // $dropdown  = json_decode(json_encode($dropdown), true);
      // $dropdown2 = json_decode(json_encode($dropdown2), true);

      return array(
        'list'      => $list,
        'nested'    => $nested,
        'dropdown'  => $dropdown,
        'dropdown2' => $dropdown2,
        'htmlist'   => $htmlist,
      );
    }


    /**
     * 
     * convert MULTIDIM/NESTED into HTML SELECT/OPTGROUP/OPTION
     * no nested optgroup allowed 
     * <optgroup> tag can only contains <options> tags = w3c standards
     *
     * @param array $array
     * @param bool $_autoCall
     * @param int $profondeur
     * @param int $it
     * @return str html string to use into <select> tag
     */
    private function _nested_to_dropdown( $array=array(), $_autoCall=false, $profondeur="", $it=0 )
    {

      //first call, reset
      if (!$_autoCall)
      {
        $this->fin=array();
        $this->root=null;
        $this->it=0;
        $this->profondeur=0;
        $this->xpath="";
        $this->parserStrFin="";
      }

      //items count
      $this->it++;


      //dim after dim
      foreach( $array as $value )
      {

        if ( count($value->children)>0 )
        {
          //if item contains children
          $this->profondeur++;

          if (!$this->root) {
            $this->root =& $this->fin;//change current node
          }

          $this->root[$value->title] = array();//prep optgroup

          $this->xpath .= $value->title."/"; //linear path

          $this->root = & $this->root[$value->title]; //define this node as root

          $this->root[$value->menu_id] = $value->title;//the optgroup is added as a normal option to be selectable

          $this->_nested_to_dropdown( $value->children, true, $this->profondeur, $this->it );//process with children
        }
        elseif ( count($value->children)==0 && isset($value->title) ) {

          //items without children
          //title is a string, without chukd: extremity reached
          $this->root[$value->menu_id] = $value->title; //each child as new option

        }

      }//foreach


      //after an item without children is added
      // returns one dim up
      if ($this->profondeur) {
        $this->profondeur--;

        $regs=array();
        $regs = explode('/',$this->xpath);
        $regs = array_filter($regs);//clear empty values

        //one dim up in the path
        $regs = array_slice($regs, 0, $this->profondeur);


        if ($regs) {

          //goes from dim 0 to dim ##
          $n =& $this->fin;
          foreach ($regs as $v) {
            $n =& $n[$v];//fin[lv1], puis fin[lv1][lv2]
          }


          //set the new root for next items
          $this->root = & $n;

          //xpath
          $this->xpath=implode('/',$regs);//reset

        }
        else{
          //reset
          $this->root =& $this->fin;
          $this->xpath='';
        }

      }

      return $this->fin;
    }


    /**
     *
     * convert MULTIDIM/NESTED into HTML SELECT/OPTGROUP/OPTION
     * multiple nested optgroups allowed !
     * 
     * @param <array> $array
     * @param <bool> $_autoCall
     * @param <str/int> $profondeur
     * @param <int> $it
     * @return <str> html string
     *
    **/
    function _nested_to_dropdown_html( $array=array(), $_autoCall=false, $profondeur="", $it=0 )
    {

      if (!$_autoCall)
      {
        $this->parserStrFin="";
        $this->it=0;
        $this->profondeur=0;
      }

      $this->it++;

      foreach( $array as $value )
      {

        if ( count($value->children)>0 )
        {
          $p = 15 * $this->profondeur;//or in your .css:  optgroup>optgroup {padding-left: 15px};
          $this->profondeur++;
          $this->parserStrFin .= '<optgroup class="submenu-title" style="padding-left:'.$p.'px" label="'.$value->title.'">'."\n";
          $this->parserStrFin .= '  <option class="submenu-item" value="'.$value->menu_id.'">'.$value->title.'</option>'."\n";
          $this->_nested_to_dropdown_html( $value->children, true, $this->profondeur, $this->it );
        }
        elseif ( count($value->children)==0 && isset($value->title) ) {
          $this->parserStrFin .= '  <option class="submenu-item" value="'.$value->menu_id.'">'.$value->title.'</option>'."\n";

        }

      }

      if ($this->profondeur)       { $this->parserStrFin .= '</optgroup>'."\n"; $this->profondeur--; } //prof = 0, on ferme le UL FirstLevelListTypeTag

      return $this->parserStrFin;
    }



    /**
     * convett FLAT en MULTIDIM/NESTED
     *
     * @param array flat $list
     * @return array multi
     * @source: php.net
     *
     * NOTE: array must be well sorted: parents items must be parsed before any of their child
     */
    private function _flat_to_nested($source)
    {
      $nodes = array();
      $tree = array();
      foreach ($source as &$node) {
        $node->children = array();
        $id = $node->menu_id;
        $parent_id = $node->parent_menu_id;
        $nodes[$id] =& $node;
        if (array_key_exists($parent_id, $nodes)) {
          $nodes[$parent_id]->children[] =& $node;
        } else {
          $tree[] =& $node;
        }
      }

      return $tree;

    }



    /**
     * convert MULTIDIM/NESTED into HTML LIST
     * 
     * @param array $array
     * @param bool $_autoCall
     * @param int $profondeur
     * @param int $it
     * @return <str> html list 
     *
    **/
    function _nested_to_ul( $array=array(), $_autoCall=false, $profondeur="", $it=0 )
    {

      if (!$_autoCall)
      {
        $this->parserStrFin="";
        $this->it=0;
        $this->profondeur=0;
      }

      $firstListType = 'ul';//first level list type
      $itemsListType = 'ul';//sub level list type

      $tag = (empty($this->profondeur) && $this->it==0) ? $firstListType : $itemsListType;
      $this->parserStrFin .= "\n".'<'.$tag.' class="level-'.$this->profondeur.'">'."\n";

      $this->it++;

      foreach( $array as $value )
      {

        if ( count($value->children)>0)
        {
          $this->profondeur++;
          $this->parserStrFin .= '  <li class="submenu-title"><h3>'. $value->title .'</h3>'."\n";
          $this->_nested_to_ul( $value->children, true, $this->profondeur, $this->it );
        }
        elseif ( count($value->children)==0 && isset($value->title) ) {
          $this->parserStrFin .= '  <li class="submenu-item">'. '<a href="#'.$value->menu_id.'">'.$value->title.'</a>' .'</li>'."\n";

        }

      }


      if ($this->profondeur == 0)       { $this->parserStrFin .= "</".$firstListType.">\n"; $this->profondeur--; }
      else if (($this->profondeur > 0)) { $this->parserStrFin .= "</".$itemsListType.">\n</li>\n"; $this->profondeur--; }

      return $this->parserStrFin;
    }

  }

  //SAMPLE USAGE:

  //DATAS:
    //the class uses FLAT array containing "objects" so here's the datas
    $list='a:8:{i:0;O:8:"stdClass":4:{s:7:"menu_id";s:1:"1";s:5:"title";s:14:"Menu principal";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"0";}i:1;O:8:"stdClass":4:{s:7:"menu_id";s:1:"2";s:5:"title";s:15:"Menu secondaire";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"0";}i:2;O:8:"stdClass":4:{s:7:"menu_id";s:1:"3";s:5:"title";s:11:"SUBMENU 1-1";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"1";}i:3;O:8:"stdClass":4:{s:7:"menu_id";s:1:"4";s:5:"title";s:11:"SUBMENU 2-1";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"2";}i:4;O:8:"stdClass":4:{s:7:"menu_id";s:1:"5";s:5:"title";s:11:"SUBMENU 1-2";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"1";}i:5;O:8:"stdClass":4:{s:7:"menu_id";s:1:"6";s:5:"title";s:11:"SUBMENU 2-2";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"2";}i:6;O:8:"stdClass":4:{s:7:"menu_id";s:1:"7";s:5:"title";s:11:"submenu 2-3";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"2";}i:7;O:8:"stdClass":4:{s:7:"menu_id";s:2:"10";s:5:"title";s:13:"submenu 1-2-1";s:3:"pos";s:1:"0";s:14:"parent_menu_id";s:1:"5";}}';
    $list=unserialize($list);

  //EXEC!
  $t = new myNested;
  $result = $t->index( $list );

  //RETURNS:
  $source = $result['list'];
  $nested = $result['nested'];
  $dropdown = $result['dropdown'];
  $dropdown2 = $result['dropdown2'];
  $htmlist = $result['htmlist'];

  echo '<pre style="border:1px solid #C00; color: #C00; background:#FFFFFE;">';
  echo "<B>SOURCE=</B>:<br/>"; print_r($source); echo "<hr/>";
  echo "<B>NESTED=</B>:<br/>"; print_r($nested); echo "<hr/>";
  echo "<B>DROPDOWN=</B>:<br/>"; highlight_string($dropdown); echo "<hr/>";
  echo "<B>DROPDOWN2=</B>:<br/>"; print_r($dropdown2); echo "<hr/>";
  echo "<B>HTMLIST=</B>:<br/>"; print_r($htmlist); echo "<hr/>";
  echo '</pre>';



  ?>

Change your code to this and see how it goes


<script>
    function doSomething()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number=" + jQuery("#nInput").val() + "$$$" + jQuery('input[name=switcher]:checked').val(), true);
        xhttp.send();
    }
    function doSomethingElse()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number2=" + jQuery("#nInput2").val() + "$$$" + jQuery('input[name=switcher2]:checked').val(), true);
        xhttp.send();
    }
</script>
<style>
    .calOut {
        position: relative;
        float: left;
        margin-right: 18px;
    }
</style>
<style media="print">
    #calContent { display: none; }
</style>
<div id="calContent" style="margin-top: 0px; margin-bottom: 50px; color:black;" class="contact_form" >

<?php
    $numname = "number";
    if (isset($_GET["number"])) {
        echo "<div><input type='text' id='nInput' name='nInput' value='" . explode("$$$", $_GET["number"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher' value='female' "; if (explode("$$$", $_GET["number"])[1] == "female") echo "checked"; echo ">Female&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='male' " . (explode("$$$", $_GET["number"])[1] == "male" ? "checked" : "") . ">Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='last' " . (explode("$$$", $_GET["number"])[1] == "last" ? "checked" : "") . ">Last name&nbsp;&nbsp;";
    }
    else {
        echo "<div><input placeholder='Enter vibration' type='text' id='nInput' name='nInput' />";
        echo "<br /><input type='radio' name='switcher' value='female' checked>Female&nbsp;&nbsp;<input type='radio' name='switcher' value='male' >Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='last' />Last name";
    }
    echo "<br /><input type='submit' id='nForm' value='Generate names' onclick='doSomething()' class='qbutton' style='margin-bottom: 45px;'/><br /></div>";

    if (isset($_GET["number2"])) {
        echo "<div><input type='text' id='nInput2' name='nInput2' value='" . explode("$$$", $_GET["number2"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher2' value='female' "; if (explode("$$$", $_GET["number2"])[1] == "female") echo "checked"; echo ">Female&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='male' " . (explode("$$$", $_GET["number2"])[1] == "male" ? "checked" : "") . ">Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='last' " . (explode("$$$", $_GET["number2"])[1] == "last" ? "checked" : "") . ">Last name&nbsp;&nbsp;";
        $numname = "number2";
    }
    else {
        echo "<div><input placeholder='Enter vibration and number, eg. Lisa 17/8' type='text' id='nInput2' name='nInput' />";
        echo "<br /><input type='radio' name='switcher2' value='female' checked>Female&nbsp;&nbsp;<input type='radio' name='switcher2' value='male' >Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='last' />Last name";
    }

    echo "<br /><input type='submit' id='nForm2' value='Generate names' onclick='doSomethingElse()' class='qbutton' /><br /></div>";

    //echo $_SERVER['HTTP_REFERER'];
    //echo "<br />";
    //if ($_SERVER['REMOTE_ADDR'] == "93.176.86.170" || $_SERVER['REMOTE_ADDR'] == "86.52.165.122")
    //  echo $_SERVER['REQUEST_URI'];

    $values = [
        "a" => 1, "i" => 1, "j" => 1, "q" => 1, "y" => 1, "å" => 1, "á" => 1, "à" => 1,
        "b" => 2, "k" => 2, "r" => 2,
        "c" => 3, "g" => 3, "l" => 3, "s" => 3, "ç" => 3,
        "d" => 4, "m" => 4, "t" => 4,
        "e" => 5, "h" => 5, "n" => 5, "x" => 5, "é" => 5, "è" => 5, "è" => "5",
        "u" => 6, "v" => 6, "w" => 6, "æ" => 6,
        "o" => 7, "z" => 7, "ø" => 7, "ô" => 7, "ó" => 7, "ò" => 7, "ö" => 7,
        "f" => 8, "p" => 8];
?>
<br />
<?php



//ini_set('memory_limit', '2048M');
error_reporting(0);
ini_set("display_errors", 0);
ini_set("log_errors", 0);
ini_set("error_reporting", 0);


    if (isset($_GET[$numname]))
    {
        $namecount = 0;
        if (is_numeric(explode("/", explode("$$$", $_GET["number"])[0])[0]))
        {
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($line));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($line)),$j,1)];
                    }
                    if ($bVal==explode("/", explode("$$$", $_GET[$numname])[0])[0] || explode("/", explode("$$$", $_GET[$numname])[0])[0] == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $line . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else if (is_numeric(explode(" ", explode("/", explode("$$$", $_GET[$numname])[0])[0])[1]))
        {
            $parm1 = explode(" ", explode("$$$", $_GET[$numname])[0]);
            $oldname = utf8_decode($parm1[0]);
            $num = explode("/", $parm1[1])[0];
            //echo "<p>" . $parm1 . "</p>";
            //echo "<p>" . $oldname . "</p>";
            //echo "<p>" . $num . "</p>";
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $linex = $parm1[0] . mb_strtolower($line);//utf8_decode(mb_strtolower($oldname . mb_strtolower($line)));
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($linex));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($linex)),$j,1)];
                    }
                    if ($bVal==$num || $num == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $linex . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else
        {
            echo "<br />Error in input";
        }
        echo "<div style='clear:both;'></div>";
    }
?>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

This should work now, I have fixed some errors in your page:


<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>    
    </head>
    <body>
        <!-- Página Principal -->
        <div id="home" data-role="page" data-title="Ponte de Lima | HOME">
            <!-- Header -->
            <h1>Ponte de Lima - HOME</h1>
            <!--Grupo de botoes do menu principal -->     
            <div data-role="controlgroup">
                <a href="#circuito_turistico"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Circuíto Turístico</a>
                <a href="#informacao_geral"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Informaçao Geral</a>
                <a href="#pertodemim"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Perto de mim</a>
                <a href="#evento"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Eventos</a>
                <a href="#monumentos"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Monumentos</a>
                <a href="#galeria"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Galeria</a>
                <a href="#servicos"
                data-transistion="flip"
                data-role="button"
                data-icon="arrow-r">Serviços</a>
                <a href="#contactos"
                data-transition="flip"
                data-role="button"
                data-icon="arrow-r">Contactos</a>
            </div>
            <div data-role="footer" data-position="fixed">            
                <center>
                    <span style="font-size:12px;">Desenvolvido por whatAdev</span>
                </center>
            </div>
        </div>
        <!--Fim da pág. Home -->

        <!-- Icon no canto superior direito com a nossa info -->
        <div data-role="page" id="info">
            <div data-role="header">
                <h1>Sobre os criadores</h1>
            </div>
            <div data-role="content">
                <p>Esta aplicaçao foi desenvolvida por Joao Pereira e Carlos Barros. Visite whatAdev.com para mais informaçoes sobre os criadores.</p>
                <a href="#"
                data-role="button"
                data-inline="true"
                data-rel="back"
                >Voltar</a>
                <a href="#home"
                data-role="button"
                data-inline="true"
                >Ínicio</a>
            </div>
        </div>
        <!-- Fim do pág. Info -->

        <!-- Inicio da página Circuito Turistico -->
        <div id="circuito_turistico" data-role="page" data-title="Ponte de Lima - Circuíto Turístico">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Circuíto Turístico</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">
                Inserir Conteudo posteriormente
            </div><!-- content -->
            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#informacao_geral"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#pertodemim"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>
                        <li><a href="#evento"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Eventos</a></li>
                        <li><a href="#monumentos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>
                        <li><a href="#galeria"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pág. Circuito Turistico -->

        <!-- Inicio da página Informaçao Geral -->
        <div id="informacao_geral" data-role="page" data-title="Ponte de Lima - Informaçao Geral">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Informaçao Geral</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">
                <div data-role="collapsible-set">
                    <div data-role="collapsible"
                    data-collapsed="false">
                        <h3>Sobre a vila</h3>
                        <p>Ponte de Lima é a vila mais antiga de Portugal e é reconhecida como um património universal, um território sem fronteiras mediador de um movimento que entende o nosso planeta como um lugar sagrado.</p></div>
                    <div data-role="collapsible">
                        <h3>Turismo em Ponte de Lima</h3>
                        <p>Ponte de Lima é berço do Turismo de Habitaçao, da casta Loureiro que distingue o Vinho Verde e do Arroz de Sarrabulho apreciado nos mais recônditos lugares do mundo. É a Vila mais florida e mais antiga de Portugal.</p></div>
                    <div data-role="collapsible">
                        <h3>Atracçoes turísticas</h3>
                        <p>Dignos de registo é a Área de Paisagem Protegida, o Festival Internacional de Jardins, a Feira do Cavalo ou mesmo o Caminho Portugues de Santiago, como pólos de atracçao turística cada vez mais internacional.</p>
                    </div>            
                </div>                          
            </div><!-- content -->
            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#circuito_turistico"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#pertodemim"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>

                        <li><a href="#evento"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Eventos</a></li>

                        <li><a href="#monumentos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>

                        <li><a href="#galeria"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pag. informacao geral -->

        <!-- Inicio da página Perto de mim -->
        <div id="pertodemim" data-role="page" data-title="Ponte de Lima - Perto de Mim">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Perto de Mim</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">
                Conteudo a aplicar posteriormente com mapas.          
            </div><!-- content -->
            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#circuito_turistico"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#informacao_geral"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>

                        <li><a href="#evento"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">evento</a></li>

                        <li><a href="#monumentos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>

                        <li><a href="#galeria"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pag. perto de mim -->

        <!-- Inicio da página evento -->
        <div id="evento" data-role="page" data-title="Ponte de Lima - Eventos">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Eventos</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">
                <div data-role="collapsible-set">
                    <div data-role="collapsible">
                        <h3>
                            Feiras Novas
                        </h3>
                        <p>
                            No segundo fim-de-semana de Setembro, realizam-se as festas do concelho que se denominam de Feiras Novas. <br/>
                            As Feiras Novas oferecem aos limianos e aos milhares de forasteiros, tres dias e outras tantas noites de cor, alegria, folia e ritmo. Para além da música, folclore e fogo de artifício, há ainda espaço para concursos pecuários, corridas de garranos, cortejos etnográfico e histórico, bandas de música, gigantones e cabeçudos, grupos de bombos e para a procissao que encerra o ciclo das romarias do Alto Minho.<br/>
                            Mas é o povo com a sua alegria e espontaneidade, a sua forma de fazer e estar na festa, as rusgas e os cantares ao desafio, o folclore em qualquer canto da vila que transforma as Feiras Novas num momento único e na romaria que é considerada o "maior congresso ao vivo da cultura popular em Portugal".
                        </p>
                    </div>
                    <div data-role="collapsible">
                        <h3>
                            Vaca das Cordas
                        </h3>
                        <p>
                            Podemos chamar-lhe a tradiçao mais tradicional de Ponte de Lima, pois perde-se no pó dos tempos a origem de tao peculiar manifestaçao. Ao final da tarde, milhares de pessoas aguardam impacientes que a Vaca das Cordas (actualmente um touro bravo) saia para as ruas e cumpra a tradiçao.<br/>
                            Até ao pôr do sol, no areal junto ao rio, as correrias, os trambolhoes e as quedas sucedem-se, numa cadencia de espectáculo e de emoçao que só acontece na Vaca das Cordas.
                        </p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Festival Expolima</h3>
                        <p>No extraordinário ambiente da Expolima, junto a suavidade das águas do Rio Lima, realiza-se o Festival Expolima.<br/>
                            Aliar a esta diversidade musical a gastronomia limiana, a beleza do Festival Internacional de Jardins, o santuário do ambiente das Lagoas, a ruralidade da Quinta Pedagógica de Pentieiros, a magnificencia do Museu dos Terceiros e toda a medievalidade que se respira em Ponte de Lima, completam todos os motivos para uma estadia nesta terra nobre rodeada pela mais bonita regiao de Portugal.</p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Festival Internacional de Jardins</h3>
                        <p>Ponte de Lima orgulha-se de ser a capital portuguesa dos jardins. Desde 2005 realiza anualmente o Festival Internacional de Jardins, iniciativa inédita em Portugal e que vem de encontro as políticas ambientais e paisagistas.<br/>
                            Todos os anos, de Maio a finais de Outubro, dezenas de milhar de visitantes descobrem doze jardins diferentes, submetidos, ou nao, a uma temática definida, que pretendem realçar as diferentes ópticas e formas de estar perante esta arte que é a construçao de jardins efémeros.<br/>
                            Juntamente com o Festival de Chaumont, em França e o Festival der Gärten, na regiao de Kamptal na Áustria, o Festival Internacional de Jardins forma a Rede Europeia de Festivais de Jardins. <br/>
                            Os jardins continuam a ser uma tradiçao em Ponte de Lima, que já venceu o Concurso Nacional de Vilas e Cidades Floridas por tres vezes, para além de ter ganho as medalhas de prata e de bronze no Concurso de Vilas e Cidades Mais Floridas da Europa.</p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Feira de Caça, Pesca e Lazer de Ponte de Lima</h3>
                        <p>A Feira de Caça, Pesca e Lazer de Ponte de Lima, pretende ser o motor de divulgaçao das alternativas a tradicional oferta turística. O evento visa divulgar todos os ramos, serviços e actividades ligadas ao sector da caça, da pesca e lazer, colmatando uma lacuna importante, numa regiao cheia de tradiçoes e potencial turístico.</p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Feira de Caça, Pesca e Lazer de Ponte de Lima</h3>
                        <p>A Feira de Caça, Pesca e Lazer de Ponte de Lima, pretende ser o motor de divulgaçao das alternativas a tradicional oferta turística. O evento visa divulgar todos os ramos, serviços e actividades ligadas ao sector da caça, da pesca e lazer, colmatando uma lacuna importante, numa regiao cheia de tradiçoes e potencial turístico.</p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Feira do Cavalo</h3>
                        <p>
                            A tradiçao equestre no concelho obrigam a uma atençao muito especial, pelo que a Feira do Cavalo é o maior certame do género realizado no norte de Portugal. Cavalos de raça, oriundos de várias regioes e cavaleiros de nomeada, dao o brilho a esta manifestaçao que transforma a zona da Expolima, em Ponte de Lima, num picadeiro gigantesco, tendo como pano de fundo o Rio Lima.
                        </p>
                    </div>

                    <div data-role="collapsible">
                        <h3>Feira Quinzenal</h3>
                        <p>
                            D. Teresa, mae de D. Afonso Henriques, primeiro Rei de Portugal, na carta de foral outorgada a Ponte de Lima em 4 de Março de 1125, refere já a sua existencia, facto que a torna a primeira feira documentada em Portugal.<br/>
                            O tempo nao acabou com esta tradiçao e quinzenalmente, as segundas-feiras (o povo chama as outras solteiras), na margem esquerda do rio, a feira mais antiga de Portugal, obrigatoriamente, continua a cumprir-se.

                            Vir mercar nas ruas artificiais criadas entre as tendas do areal é uma experiencia única para quem quiser viver um pouco do que resta dos velhos hábitos medievais, pelo que nao pode nem deve deixar de o fazer.
                        </p>
                    </div>
                </div>
            </div><!-- content -->



            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#circuito_turistico"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#informacao_geral"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#pertodemim"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>

                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">evento</a></li>

                        <li><a href="#monumentos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>

                        <li><a href="#galeria"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pag. evento -->

        <!-- Inicio da página Monumentos -->
        <div id="monumentos" data-role="page" data-title="Ponte de Lima - Monumentos">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Monumentos</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">

            </div><!-- content -->
            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#circuito_turistico"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#informacao_geral"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#pertodemim"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>

                        <li><a href="#evento"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Eventos</a></li>

                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>

                        <li><a href="#galeria"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pag. monumentos -->

        <!-- Inicio da página Circuito Turistico -->
        <div id="galeria" data-role="page" data-title="Ponte de Lima - Galeria">
            <div data-role="header" data-position="fixed"data-id="ptl_header">
                <h1>Galeria</h1>
                <a href="#home" data-icon="home" data-transition="pop" data-iconpos="notext"></a>
                <a href="#info"
                data-icon="info"
                data-iconpos="notext"
                data-rel="dialog"
                class="ui-btn-right"
                data-transition="pop"
                >Info</a>
            </div>
            <div data-role="content">
                Inserir Conteudo posteriormente
            </div><!-- content -->
            <div data-role="footer" data-position="fixed" data-id="ptl_footer">            
                <div data-role="navbar">    
                    <ul>
                        <li><a href="#circuito_turistico"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Circuíto Turístico</a></li>
                        <li><a href="#informacao_geral"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Informaçao Geral</a></li>
                        <li><a href="#pertodemim"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Perto de mim</a></li>
                        <li><a href="#evento"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Eventos</a></li>
                        <li><a href="#monumentos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Monumentos</a></li>
                        <li><a href="#"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Galeria</a></li>
                        <li><a href="#servicos"
                            data-transistion="flip"
                            data-role="button"
                            data-icon="arrow-r">Serviços</a></li>
                        <li><a href="#contactos"
                            data-transition="flip"
                            data-role="button"
                            data-icon="arrow-r">Contactos</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- Fim da pág. Galeria -->
    </body>
</html>

Complete working code. I know this is long, but it's a sure-shot way used by Wordpress.


<?php

function seems_utf8($str) 
{
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
        }
    }
    return true;
}

/**
 * Converts all accent characters to ASCII characters.
 *
 * If there are no accent characters, then the string given is just returned.
 *
 * @param string $string Text that might have accent characters
 * @return string Filtered string with replaced "nice" characters.
 */
function remove_accents($string) {
    if ( !preg_match('/[\x80-\xff]/', $string) )
        return $string;

    if (seems_utf8($string)) {
        $chars = array(
        // Decompositions for Latin-1 Supplement
        chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
        chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
        chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
        chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
        chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
        chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
        chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
        chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
        chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
        chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
        chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
        chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
        chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
        chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
        chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
        chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
        chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
        chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
        chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
        chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
        chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
        chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
        chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
        chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
        chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
        chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
        chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
        chr(195).chr(191) => 'y',
        // Decompositions for Latin Extended-A
        chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
        chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
        chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
        chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
        chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
        chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
        chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
        chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
        chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
        chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
        chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
        chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
        chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
        chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
        chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
        chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
        chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
        chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
        chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
        chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
        chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
        chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
        chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
        chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
        chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
        chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
        chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
        chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
        chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
        chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
        chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
        chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
        chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
        chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
        chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
        chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
        chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
        chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
        chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
        chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
        chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
        chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
        chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
        chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
        chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
        chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
        chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
        chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
        chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
        chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
        chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
        chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
        chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
        chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
        chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
        chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
        chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
        chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
        chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
        chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
        chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
        chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
        chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
        chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
        // Euro Sign
        chr(226).chr(130).chr(172) => 'E',
        // GBP (Pound) Sign
        chr(194).chr(163) => '');

        $string = strtr($string, $chars);
    } else {
        // Assume ISO-8859-1 if not UTF-8
        $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
            .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
            .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
            .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
            .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
            .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
            .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
            .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
            .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
            .chr(252).chr(253).chr(255);

        $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";

        $string = strtr($string, $chars['in'], $chars['out']);
        $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
        $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
        $string = str_replace($double_chars['in'], $double_chars['out'], $string);
    }

    return $string;
}


$str = "ÈâuÑ";
echo remove_accents($str); // Output: EauN
?>

So the problem was in the makefile. I didn't realize the AVR was listed in the makefile that I downloaded from the instructions from the hackaday tutorial. Once I changed the MCU, AVRDUDE_PROGRAMMER, and PORT in the makefile it worked like a charm.


# WinAVR Sample makefile written by Eric B. Weddington, J�rg Wunsch, et al.
# Modified (bringing often-changed options to the top) by Elliot Williams

# make all = Make software and program
# make clean = Clean out built project files.
# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB).
# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio
#                4.07 or greater).
# make program = Download the hex file to the device, using avrdude.  Please
#                customize the avrdude settings below first!
# make filename.s = Just compile filename.c into the assembler code only
# To rebuild project do "make clean" then "make all".

# Microcontroller Type
# MCU = attiny13
# MCU = attiny2313
# MCU = atmega8
# MCU = atmega168
MCU = atmega32 # CHANGED THIS TO THE MCU THAT I'M TRYING TO PROGRAM

# Target file name (without extension).
TARGET = main

# Programming hardware: type avrdude -c ?
# to get a full listing.
# AVRDUDE_PROGRAMMER = dapa              # official name of 
# AVRDUDE_PROGRAMMER = dragon_isp
AVRDUDE_PROGRAMMER = avrisp # CHANGED THIS TO THE ISP I'M USING TO PROGRAM

AVRDUDE_PORT = COM3         # CHANGED THIS TO THE PORT ARDUINO IS CONNECTED TO
#AVRDUDE_PORT = usb         # linux for dragon
#AVRDUDE_PORT = /dev/parport0           # linux
#AVRDUDE_PORT = lpt1               # windows

############# Don't need to change below here for most purposes  (Elliot)

# Optimization level, can be [0, 1, 2, 3, s]. 0 turns off optimization.
# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
OPT = s

# Output format. (can be srec, ihex, binary)
FORMAT = ihex

# List C source files here. (C dependencies are automatically generated.)
SRC = $(TARGET).c

# If there is more than one source file, append them above, or modify and
# uncomment the following:
#SRC += foo.c bar.c

# You can also wrap lines by appending a backslash to the end of the line:
#SRC += baz.c \
#xyzzy.c



# List Assembler source files here.
# Make them always end in a capital .S.  Files ending in a lowercase .s
# will not be considered source files but generated files (assembler
# output from the compiler), and will be deleted upon "make clean"!
# Even though the DOS/Win* filesystem matches both .s and .S the same,
# it will preserve the spelling of the filenames, and gcc itself does
# care about how the name is spelled on its command-line.
ASRC = 


# List any extra directories to look for include files here.
#     Each directory must be seperated by a space.
EXTRAINCDIRS = 


# Optional compiler flags.
#  -g:        generate debugging information (for GDB, or for COFF conversion)
#  -O*:       optimization level
#  -f...:     tuning, see gcc manual and avr-libc documentation
#  -Wall...:  warning level
#  -Wa,...:   tell GCC to pass this to the assembler.
#    -ahlms:  create assembler listing
CFLAGS = -g -O$(OPT) \
-funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums \
-Wall -Wstrict-prototypes \
-Wa,-adhlns=$(<:.c=.lst) \
$(patsubst %,-I%,$(EXTRAINCDIRS))


# Set a "language standard" compiler flag.
#   Unremark just one line below to set the language standard to use.
#   gnu99 = C99 + GNU extensions. See GCC manual for more information.
#CFLAGS += -std=c89
#CFLAGS += -std=gnu89
#CFLAGS += -std=c99
CFLAGS += -std=gnu99



# Optional assembler flags.
#  -Wa,...:   tell GCC to pass this to the assembler.
#  -ahlms:    create listing
#  -gstabs:   have the assembler create line number information; note that
#             for use in COFF files, additional information about filenames
#             and function names needs to be present in the assembler source
#             files -- see avr-libc docs [FIXME: not yet described there]
ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs 



# Optional linker flags.
#  -Wl,...:   tell GCC to pass this to linker.
#  -Map:      create map file
#  --cref:    add cross reference to  map file
LDFLAGS = -Wl,-Map=$(TARGET).map,--cref



# Additional libraries

# Minimalistic printf version
#LDFLAGS += -Wl,-u,vfprintf -lprintf_min

# Floating point printf version (requires -lm below)
#LDFLAGS += -Wl,-u,vfprintf -lprintf_flt

# -lm = math library
LDFLAGS += -lm


# Programming support using avrdude. Settings and variables.


AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex
#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep

AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER)

# Uncomment the following if you want avrdude's erase cycle counter.
# Note that this counter needs to be initialized first using -Yn,
# see avrdude manual.
#AVRDUDE_ERASE += -y

# Uncomment the following if you do /not/ wish a verification to be
# performed after programming the device.
#AVRDUDE_FLAGS += -V

# Increase verbosity level.  Please use this when submitting bug
# reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude> 
# to submit bug reports.
#AVRDUDE_FLAGS += -v -v

#Run while cable attached or don't
#AVRDUDE_FLAGS += -E reset #keep chip disabled while cable attached
#AVRDUDE_FLAGS += -E noreset

#AVRDUDE_WRITE_FLASH = -U lfuse:w:0x04:m #run with 8 Mhz clock

#AVRDUDE_WRITE_FLASH = -U lfuse:w:0x21:m #run with 1 Mhz clock #default clock mode

#AVRDUDE_WRITE_FLASH = -U lfuse:w:0x01:m #run with 1 Mhz clock no start up time

# ---------------------------------------------------------------------------

# Define directories, if needed.
DIRAVR = c:/winavr
DIRAVRBIN = $(DIRAVR)/bin
DIRAVRUTILS = $(DIRAVR)/utils/bin
DIRINC = .
DIRLIB = $(DIRAVR)/avr/lib


# Define programs and commands.
SHELL = sh

CC = avr-gcc

OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size


# Programming support using avrdude.
AVRDUDE = avrdude


REMOVE = rm -f
COPY = cp

HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) -AC --mcu=$(MCU) $(TARGET).elf



# Define Messages
# English
MSG_ERRORS_NONE = Errors: none
MSG_BEGIN = -------- begin --------
MSG_END = --------  end  --------
MSG_SIZE_BEFORE = Size before: 
MSG_SIZE_AFTER = Size after:
MSG_COFF = Converting to AVR COFF:
MSG_EXTENDED_COFF = Converting to AVR Extended COFF:
MSG_FLASH = Creating load file for Flash:
MSG_EEPROM = Creating load file for EEPROM:
MSG_EXTENDED_LISTING = Creating Extended Listing:
MSG_SYMBOL_TABLE = Creating Symbol Table:
MSG_LINKING = Linking:
MSG_COMPILING = Compiling:
MSG_ASSEMBLING = Assembling:
MSG_CLEANING = Cleaning project:




# Define all object files.
OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) 

# Define all listing files.
LST = $(ASRC:.S=.lst) $(SRC:.c=.lst)

# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS)
ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)



# Default target: make program!
all: begin gccversion sizebefore $(TARGET).elf $(TARGET).hex $(TARGET).eep \
    $(TARGET).lss $(TARGET).sym sizeafter finished end
    $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM)

# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
begin:
    @echo
    @echo $(MSG_BEGIN)

finished:
    @echo $(MSG_ERRORS_NONE)

end:
    @echo $(MSG_END)
    @echo


# Display size of file.
sizebefore:
    @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi

sizeafter:
    @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi



# Display compiler version information.
gccversion : 
    @$(CC) --version




# Convert ELF to COFF for use in debugging / simulating in
# AVR Studio or VMLAB.
COFFCONVERT=$(OBJCOPY) --debugging \
    --change-section-address .data-0x800000 \
    --change-section-address .bss-0x800000 \
    --change-section-address .noinit-0x800000 \
    --change-section-address .eeprom-0x810000 


coff: $(TARGET).elf
    @echo
    @echo $(MSG_COFF) $(TARGET).cof
    $(COFFCONVERT) -O coff-avr $< $(TARGET).cof


extcoff: $(TARGET).elf
    @echo
    @echo $(MSG_EXTENDED_COFF) $(TARGET).cof
    $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof




# Program the device.  
program: $(TARGET).hex $(TARGET).eep
    $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM)




# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
    @echo
    @echo $(MSG_FLASH) $@
    $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@

%.eep: %.elf
    @echo
    @echo $(MSG_EEPROM) $@
    -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
    --change-section-lma .eeprom=0 -O $(FORMAT) $< $@

# Create extended listing file from ELF output file.
%.lss: %.elf
    @echo
    @echo $(MSG_EXTENDED_LISTING) $@
    $(OBJDUMP) -h -S $< > $@

# Create a symbol table from ELF output file.
%.sym: %.elf
    @echo
    @echo $(MSG_SYMBOL_TABLE) $@
    avr-nm -n $< > $@



# Link: create ELF output file from object files.
.SECONDARY : $(TARGET).elf
.PRECIOUS : $(OBJ)
%.elf: $(OBJ)
    @echo
    @echo $(MSG_LINKING) $@
    $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)


# Compile: create object files from C source files.
%.o : %.c
    @echo
    @echo $(MSG_COMPILING) $<
    $(CC) -c $(ALL_CFLAGS) $< -o $@


# Compile: create assembler files from C source files.
%.s : %.c
    $(CC) -S $(ALL_CFLAGS) $< -o $@


# Assemble: create object files from assembler source files.
%.o : %.S
    @echo
    @echo $(MSG_ASSEMBLING) $<
    $(CC) -c $(ALL_ASFLAGS) $< -o $@






# Target: clean project.
clean: begin clean_list finished end

clean_list :
    @echo
    @echo $(MSG_CLEANING)
    $(REMOVE) $(TARGET).hex
    $(REMOVE) $(TARGET).eep
    $(REMOVE) $(TARGET).obj
    $(REMOVE) $(TARGET).cof
    $(REMOVE) $(TARGET).elf
    $(REMOVE) $(TARGET).map
    $(REMOVE) $(TARGET).obj
    $(REMOVE) $(TARGET).a90
    $(REMOVE) $(TARGET).sym
    $(REMOVE) $(TARGET).lnk
    $(REMOVE) $(TARGET).lss
    $(REMOVE) $(OBJ)
    $(REMOVE) $(LST)
    $(REMOVE) $(SRC:.c=.s)
    $(REMOVE) $(SRC:.c=.d)
    $(REMOVE) *~

# Automatically generate C source code dependencies. 
# (Code originally taken from the GNU make user manual and modified 
# (See README.txt Credits).)
#
# Note that this will work with sh (bash) and sed that is shipped with WinAVR
# (see the SHELL variable defined above).
# This may not work with other shells or other seds.
#
%.d: %.c
    set -e; $(CC) -MM $(ALL_CFLAGS) $< \
    | sed 's,\(.*\)\.o[ :]*,\1.o \1.d : ,g' > $@; \
    [ -s $@ ] || rm -f $@


# Remove the '-' if you want to see the dependency files generated.
-include $(SRC:.c=.d)



# Listing of phony targets.
.PHONY : all begin finish end sizebefore sizeafter gccversion coff extcoff \
    clean clean_list program

Recommend

How To Install Linux, Nginx, MySQL, PHP (LEMP) Stack on CentOS 8 Step 3 — Installing PHP-FPM

How To Install Linux, Nginx, MySQL, PHP (LEMP) Stack on CentOS 8 Step 2 — Installing MariaDB

How To Install Linux, Nginx, MySQL, PHP (LEMP) Stack on CentOS 8 Step 1 — Installing the Nginx Web Server

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04 Conclusion Want to learn more? Join the DigitalOcean Community! Still looking for an answer?

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04 Step 3 — Implementing Pagination with PHP

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04 Step 2 — Displaying MySQL Records Without Pagination

How To Implement Pagination in MySQL with PHP on Ubuntu 18.04 Step 1 — Creating a Database User and a Test Database

Results

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Testing Fail2Ban Policies

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Getting Info About Enabled Jails

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Activating your Nginx Jails

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Adding the Filters for Additional Nginx Jails

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Adjusting the General Settings within Fail2Ban Changing Defaults

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Adjusting the General Settings within Fail2Ban

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Install Fail2Ban

How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04 Installing Nginx and Configuring Password Authentication

Comment installer Linux, Nginx, MySQL, PHP (pile LEMP) sur Ubuntu 20.04 Étape 6 — Tester la connexion à la base de données à partir de PHP (facultatif)

Comment installer Linux, Nginx, MySQL, PHP (pile LEMP) sur Ubuntu 20.04 Étape 5 – Tester PHP avec Nginx

Comment installer Linux, Nginx, MySQL, PHP (pile LEMP) sur Ubuntu 20.04 Étape 4 — Configuration de Nginx pour utiliser le processeur PHP