Construction of PHP/Javascript replace function - php

I would like to ask you for some help with my problem.
I have this php code, which I use to clean $pname from prepositions, white spaces, numbers etc. to make it more suitable for sorting.
$prepositions = array(" ", "tert-", "dl-"); //only a part of all
$patterns = array("'([0-9])'si", "/\b\w\b\s?/", "/[^a-zA-Z0-9\s]/");
$sname = preg_replace($patterns, '', str_replace($prepositions, "", strtolower($pname])));
I am trying convert this code to javascript but code is so massive. Here is part of it:
function createsname ()
{
if(document.getElementById('pname').value != '')
{
var myString = new String();
myString = document.getElementById('pname').value.toLowerCase();
var reg0 = new RegExp(" ");
var sname0 = myString.replace(reg0, "");
var reg1 = new RegExp(/\d/g);
var sname = sname0.replace(reg1, "");
document.getElementById('sname').value = sname;
}
}
Examples of php results:
1,2-Bis(3-Methylthiophene2-yl)ethane-1,2-dione
bismethylthiopheneylethanedione
4H-Cyclopenta[2,1-b3,4-b]dithiophene
cyclopentadithiophene
5-Acetyl-2-amino-4-(2-furanyl)-6-methyl-4H-pyran-3-carbonitrile
acetylaminofuranylmethylpyrancarbonitrile
5-Acetyl-2-amino-4-(4-methoxyphenyl)-6-methyl-4H-pyran-3-carbonitrile
acetylaminomethoxyphenylmethylpyrancarbonitrile
5-Acetyl-2-amino-6-methyl-4-phenyl-4H-pyran-3-carbonitrile
acetylaminomethylphenylpyrancarbonitrile
Tri-O-acetyl-D-glucal
acetylglucal
5-Amino-1,3-dimethyltricyclo(3,3,1,13,7) dekane hydrochloride
aminodimethyltricyclodekanehydrochloride
DL-2-Amino-1-propanol
aminopropanol
(S)-(+)-2-Amino-1-propanol
aminopropanol
a-(3-Aminopropyl)-w-(3-aminopropoxy)-poly (oxy-1,2-ethanediyl)
aminopropylaminopropoxypolyoxyethanediyl
N-(3'-Aminopropyl)-2-pyrrolidone
aminopropylpyrrolidone
1,1,1-(5,5,5-benzene-1,3,5-triyl-tri-thiophen-2-yl)-tris-ethanone
benzenetriyltrithiophenyltrisethanone
N-[(1,4-Benzodioxane-2-yl)carboxyl]piperazine
benzodioxaneylcarboxylpiperazine
(3R)-3-{[(Benzyloxy)carbonyl]amino}butanoic acid
benzyloxycarbonylaminobutanoicacid
1,5-Bis-(2-furanyl)-1,4-pentadiene-3-one
bisfuranylpentadieneone
1-[N,N-Bis(2-hydroxyethyl)amino]-2-propanol
bishydroxyethylaminopropanol
Bisphenol A bis(chloroformate)
bisphenolabischloroformate
Bisphenol A diacetate
bisphenoladiacetate
5''-Bromo-2,2'-5',2''-terthiophene-5-carboxaldehyde
bromoterthiophenecarboxaldehyde
tert-Butyldimethylamine
butyldimethylamine
(E)-3-Chloro-2-methyl-3-(2-thienyl)acrolein
chloromethylthienylacrolein
alpha-Cyano-4-hydroxycinnamic acid
cyanohydroxycinnamicacid
Di-tert-butyl dicarbonate
dibutyldicarbonate
trans-1,4-Dichloro-2-butene
dichlorobutene
a,a-Dichloromethyl methyl ether
dichloromethylmethylether
2,2-Dimethyl-1,3-dioxolane-4-methanol p-toluenesulfonate
dimethyldioxolanemethanolptoluenesulfonate
(R)-2,2-Dimethyl-1,3-dioxolane-4-methanol p-toluenesulfonate
dimethyldioxolanemethanolptoluenesulfonate
4a(R),9b(S)-(-)-cis-2,8-Dimetyl-2,3,4,4a,5,9b-hexahydro-1H-pyrido[4,3-b]indol
dimetylhexahydropyridoindol
4,4'-Dipyridyl N,N'-dioxide hydrate
dipyridylndioxidehydrate
Ethyl 1H-pyrazole-3-carboxylate
ethylpyrazolecarboxylate
Methyl 1H-benzo[4,5]furo[3,2-b]pyrrole-2-carboxylate
methylhbenzofuropyrrolecarboxylate
Methyl 4H-furo[3,2-b]pyrrole-5-carboxylate
methylfuropyrrolecarboxylate
4-Oxo-2,2,6,6-tetramethylpiperidinoxy
oxotetramethylpiperidinoxy
3-Oxo-3-(2-thienyl)propanenitrile
oxothienylpropanenitrile
1,4-Pentadien-3-ol
pentadienol
N-[3-Phenylcoumarinyl-(7)]-N'-(g-N,N'-dimethylaminopropyl)-urea
phenylcoumarinyldimethylaminopropylurea
N,N',N'',N'''-Tetraacetylglycouril
tetraacetylglycouril
2,3,4,6-Tetra-O-benzoyl-b-D-glucopyranosyl isothiocyanate
tetrabenzoylglucopyranosylisothiocyanate
DL-1,2,3,4-Tetrachlorobutane
tetrachlorobutane
2,4,6-Tri-tert-butylaniline
tritertbutylaniline
1,3,5-Tri-tert-butylbenzene
tritertbutylbenzene
3-Amino-2,3,4,5-tetrahydro-2-oxo-2H-1-benzazepin
aminotetrahydrooxobenzazepin
Tris(3-sulfonatophenyl)phosphine hydrate, sodium salt
trissulfonatophenylphosphinehydratesodiumsalt
2-(Tritylamino)-a-(methoxyimino)-4-thiazoleacetic acid hydrochloride
tritylaminomethoxyiminothiazoleaceticacidhydrochloride
So if you have ideas how can i write it in javascript please, help me.

var myString = document.getElementById('pname').value.toLowerCase();
var replaces = [" ", "tert-", "dl-", /([0-9])/si, /\b\w\b\s?/, /[^a-zA-Z0-9\s]/];
for ( var k in replaces ) {
myString = myString.replace(replaces[k], "");
}
Brad Christie proposition:
for ( var k = 0; k < replaces.length; k++ ) {
myString = myString.replaces(replace[k], "");
}

Well, based on the examples you gave and what I could test, here's what I came up with:
String.prototype.Lukas = function(){
return this.toLowerCase().replace(/(\(.*?\)|\[.*?\]|\b\w\b\s?|(?:dl|tert|\d+[a-z]){1,4}-|\W|\d)/ig, '');
};
DEMO
Again, only based on what I could see. Use it like this:
// assign the original string to a variable
var original = '1,2,4-Triazolo-[4,3,a]pyridin-3(2H)-one';
// then get the desired result using "Lukas()"
var result = original.Lukas();

Related

How to put object into string and print

I have a script that takes variables from an html form and sends them to a php script. I query new data based on these numbers and format them into a string to be sent back to the script. The problem is that my php variables aren't printing and I think it is because they are objects. Here is my code:
//GET VENDOR PO NUMBER AND APPEND ONCHANGE OF # OF EXISTING POS
$('#numvendpo').mouseover(function(){
var countpre = $(this).val();
var p = $('#pro').val();
var c = $('#custponumhold').val();
var v = $('#vendorid').val();
var cp = (parseInt(countpre)+1);
var data_String;
data_String = 'p='+p+'&c='+c+'&v='+v+'&cp='+cp;
$.post('ft-final-v-po-num.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
});
});
I then post the values to this php script:
<?php
require "../inc/dbinfo.inc";
$p = $_POST['p'];
$c =$_POST['c'];
$v = $_POST['v'];
$cp = $_POST['cp'];
if ($c == 'null') { //cant use (!$customerpo) because $customerpo is passing the string of 'null' instead of the actual null value
$c = NULL; //so we change that to the actual null value
}
$getprojectnum = "SELECT ProjectNumber FROM tblProjects WHERE PROJECTNOID = '$p'"; //check
$getcustomerpo = "SELECT SequentialPONum FROM tblCustomerPOs WHERE CustomerPOID = '$c'"; //check
$getvendornum = "SELECT VendorNumber FROM tblVendors WHERE VENDORID = '$v'"; //check
$acpnhold = $conn->query($getprojectnum);
$accphold = $conn->query($getcustomerpo);
$acvnhold = $conn->query($getvendornum);
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
if($c){
$string = $acpn.'-'.$accp.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}elseif(!$c){
$string = $acpn.'-'.$acvn.'-'.$cp;
echo json_encode($string);
exit();
}else{
echo json_encode('Error');
exit();
}
?>
The response on my webpage is ---2 instead of (ex: 18000-1-2-2). As mentioned earlier I think it is because they are objects but I am not quite sure. Any advice is appreciated.
Your problem is with this bit:
$acpn = mysqli_fetch_object($acpn);
$accp = mysqli_fetch_object($accp);
$acvn = mysqli_fetch_object($acvn);
From the php docs:
object mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] )
Your $acpn $accp and $acvn are not result objects. They are not even defined before you use them in those calls.
This should get the single column from each query result:
$acpn = $acpnhold->fetch_row()[0];
$accp = $accphold->fetch_row()[0];
$acvn = $acvnhold->fetch_row()[0];
Bear in mind you still have a major SQL Injection vulnerability with the original query calls.
Try like this code below:
$.ajax({
type: 'POST',
url: 'ft-final-v-po-num.php',
data: {
'p': p,
'c': c,
'v': v,
'cp': cp
},
success: function(msg){
var data = jQuery.parseJSON(data);
$('#vendponum').val(data);
}
});

%20 and other misc stuff in my dynamic text

How do I get the html space characters out of my dynamic text loaded from a text file?
This is what my loaded text looks like in my .swf:
Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D
And it's my actionscript:
var select_obj:LoadVars = new LoadVars();
select_obj.onLoad = function(success:Boolean) {
if (success) {
isi.text = select_obj;
trace (select_obj);
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
select_obj.sendAndLoad(filepath + "morfologi.php", select_obj, "GET");
Here is my PHP script:
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ("SELECT isi FROM materi WHERE id = 1");
$nRows = mysql_num_rows($qResult);
$rString ="";
for ($i=0; $i< $nRows; $i++){
$row = mysql_fetch_array($qResult);
$rString .= $row['isi'];
}
echo $rString;
?>
To get your values sent by your script, you should return them as a URL-encoded query string containing name/value pairs like this :
message=hello&from=user1&to=user2
which can be returned by your PHP script :
<?php
echo "message=hello&from=user1&to=user2";
?>
then the LoadVars object will decode (parse) that variable string automatically for you as properties of the LoadVars object :
var result:LoadVars = new LoadVars();
result.onLoad = function(success:Boolean) {
if (success) {
trace(result.message); // gives : hello
trace(result.from); // gives : user1
trace(result.to); // gives : user2
trace(result); // gives : to=user2&from=user1&message=hello&onLoad=%5Btype%20Function%5D
} else {
trace('error !');
}
};
result.sendAndLoad(filepath, result);
Hope that can help.
Use urldecode() function:
<?PHP
$string = "Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D";
//$string = $_GET['variable'];
$rString = urldecode($string);
echo $rString;
I wanna erase %20, %2E%2E%2E%, and etc..
For that you can try either decodeURIComponent or just decodeURI. Read that manual for differences (but for your current result, any of these two is good).
An example with your code :
var result:LoadVars = new LoadVars();
var filepath:String;
filepath = "localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
result.onLoad = function(success:Boolean)
{
if ( success )
{
text_morfo.text = result;
text_morfo = decodeURIComponent( text_morfo );
trace("success route : "); trace( text_morfo );
}
else { trace("error in result..."); }
}
Also I don't know what else your AS & PHP code will add later so if you need a quick testing tool you can try this link. Just put your traced results into the bottom box and choose option (like unescape, decodeURI etc). This will quickly help you see which command is best to use in your AS code.

compare image similarity using php

I am searching for a way to identify similar png images with same size. The images are not the exact duplicates. For example If one image has a clip art of a bird, and another image has the same clip art but it is rotated, I want to identify both of them are similar. I want to write an algorithm do this using php.I have tried out this using javasript. What i am doing is convert the image into base64 and compare both the values using hamming distance. But as far I know this will not identify advanced techniques such as scaling, rotating. So what I want it to write an algorithm to do those things in php.Any ideas? This is what I have tried out using javascript and html5 canvas.
function newFunction()
{
var imageHeight = image.naturalHeight;
var imageWidth = image.naturalWidth;
var image2Height = image2.naturalHeight;
var image2Width = image2.naturalWidth;
var data3=[];
var imageData = context.getImageData(0,0,imageWidth,imageHeight);
var image2Data = context2.getImageData(0,0,image2Width,image2Height);
var data = imageData.data;
var data2 = image2Data.data;
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
//str = String.fromCharCode.apply(null, data); // "ÿ8É"
// str2 = String.fromCharCode.apply(null, data2); // "ÿ8É"
// to Base64
b64 = _arrayBufferToBase64(data);
b64_2 = _arrayBufferToBase64(data2 );
console.log("64 base"+b64_2);
//
var toReturn = 0;
var firstBytes =new Uint8Array(1024);
var secondBytes=new Uint8Array(1024);
var different=new Uint8Array(1024);
// firstBytes = Convert.FromBase64String(first64);
// secondBytes = Convert.FromBase64String(second64);
different = 0;
var mylength;
if(b64.length>b64_2.length)
{
mylength=b64.length;
}
else
{
mylength=b64_2.length;
}
for (var index = 0; index < mylength; index++) {
different = (b64[index] ^ b64_2[index]);
while (different != 0) {
toReturn++;
different &= different - 1;
}
}
var percentage=(toReturn/((image2Height*image2Width)*2))*100;
if(percentage >=100)
{
percentage=100;
}
alert("Difference is "+percentage+" to return" +toReturn + " data1 length"+data.length+ " data2 length"+data2.length);
}
This function works well without any errors. But it won't recognized advanced features like scaling and rotating. Give me some ideas how to do this using php.

Pass a PhP string to Mootools in Wordpress

I have a foreach loop that creates a string in php , I'm unable to pass the string value to mootools in wordpress (I'm integrating a MooTool function ) :::
I need to substitute the "hard coded" image URL's in the new Array() (below) with a variable created from my php string eg. new Array( $myimageurl ) :::
I've created a var from the php string even tried json_encode , with no luck :::
window.addEvent("domready", function(){
var counter = 0;
var images = new Array('http://localhost/square/wp-content/uploads/2011/10/test-foo/foo.jpg','http://localhost/square/wp-content/uploads/2011/10/test-foo/foo1.jpg');
er, why not just:
var foo= <?=json_encode(Array("foo.jpg", "bar.jpg"))?>;
EDIT
Since you implied in a comment your files source is comma separated, then do this instead:
<? $files = "foo.jpg,bar.jpg"; ?>
var foo = <?=json_encode(explode(',', $files))?>;
where the array could be anything of any length, read from wherever. it will result in an array literal looking like so:
var foo = ["foo.jpg","bar.jpg"];
// eg use.
foo.each(function(img) {
new Element("img", {src: img}).inject(document.body);
));
nb: just noticed #Marc B has already mentioned json_encode. sorry, will delete
try:
var images = new Array('<?php echo $miImageUrl[0];?>', '<?php echo $miImageUrl[1];?>');
Other way:
<?php
//sample data
$descargables[0] = 'cero';
$descargables[1] = 'uno';
$descargables[2] = 'dos';
$descargables[3] = 'tres';
// end sample data
$arrayToJs="var descargables = new Array();";
for ($i=0; $i < count($descargables); $i++) {
$arrayToJs .= "descargables[" . $i . "]='" . $descargables[$i]. "';";
}
?>
<script>
<?php echo $arrayToJs;?>
idx = 3;
alert("descargable:" + descargables[idx]);
</script>

Accessing json array by string? (Converting string to var. name)

I'm trying to post the "lang_id" var. to "get_lang.php" with jquery to get (json) data.
But I can't access the data.
Now trying to do
var r = $(this).attr('rel');
var v = data.r;
But this doesn't work because of "r" is string IMO.
Also tried
data.window[r] // but...
"get_lang.php";
$lang_id = (int) ($_POST['lang_id']);
if($lang_id == 1)
{
$lang['simple'] = 'aaa';
$lang['array'] = 'bbb';
}
if($lang_id == 2)
{
$lang['simple'] = 'ccc';
$lang['array'] = 'ddd';
}
print json_encode($lang);
my.js;
$.post("get_lang.php", { "lang_id": 2}, function(data){
$('.lang').each(function() {
var r = $(this).attr('rel');
var v = data.r;
$(this).text(v);
});
},"json");
thanks for help.
Try
var v = data[r];
The dot notation interprets r as a string and not as a variable.
I think maybe you need to tell jQuery the right content type. Put this at the TOP of your get_lang.php file
header("Content-Type: application/json");
And see if jQuery likes it.

Categories