PHP - Switching From Ereg_replace To Preg_match Syntax Help
Hello all,
I need to switch my code from ereg_replace to preg_match but I'm having trouble figuring out how to get the syntax right for this and keep the same functionality. $vendor_ID = ereg_replace("^\*","",$key); Any advice on how to maintain this functionality but use non-deprecated methods? Similar TutorialsI had this code but now I need to change it to newer preg_replace function Can someone help me to do it please? Here is the code: $newString = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" target=\"_blank\">\\0</a>", $originalString); Thanks in advance. I am interested in just this little snippet of code I am writing for a basic TCP socket server in PHP. Just basically goes along the lines of this: Code: [Select] <?php $value = ereg_replace("\n\t\r", "", trim($input)).chr(); It's actually regarding the chr() I know actually its nothing to do with the regular expression replace but what does it actually mean to PHP? I mean I am just using it as an output from a socket_read (as that's what $input is assigned to the value of), but what does the char(0) mean? I mean I seem to remember it being knowing the end of a line of data once the clients sent data into the stream PHP looks at chr(0) as the end of the line of data is that the right way of thinking about this logically? Any helps appreciated, trying to explain such a topic on my blog and I am confused about what to say about that one little bit, I know it's not really part of the regular expression but what does it actually do? Again massive thanks in advance for any replies, Jeremy. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=307671.0 $customer_contact_id = preg_replace("`", "", $customer_contact_id); Am I doing something wrong? Every page that used the eregi_function, I changed to have it utilize the preg_function (because I saw a Youtube video telling me to do so). Now, every variable I perform the above on acts as if it doesn't exist. This has totally destroyed my system. What do I need to do here to fix things? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=347016.0 I have been looking at this code most of the morning and do not have a clue what is wrong with the code. I am hoping its not a stupid mistake, can someone please help me out? thank you
<title>Inputing Travel Detials</title> <header> <h1 align="center"> Adding Travel Detials </h1> <body> <p> <center><img src="cyberwarfareimage1.png" alt="Squadron logo" style="width:200px;height:200px" style="middle"></center> <table border="1"> <tr> <td><a href="index.php"> Home Page </a></td> <td><a href="administratorhomepage.html">Administrator Home Page </a></td> <td><a href="viewhomepage.html">View Home Page </a></td> <td><a href="Inputhomepage.html">Input Home Page </a></td> <td><a href="traveldetials.html">Enter More Travel Detials </a></td> </table> </p> <?php include "connection.php"; $Applicant_ID = $_POST["Applicant_ID"]; $Method_Of_Travel = $_POST["Method_Of_Travel"]; $Cost = $_POST["Cost"]; $ETA = $_POST["ETA"]; $Main_Gate_Advised = $_POST["Main_Gate_Advised"]; $query = ("UPDATE `int_board_applicant` SET `Method_Of_Travel`=`$Method_Of_Travel', `Cost`=`$Cost', `ETA`='$ETA', `Main_Gate_Advised`='$Main_Gate_Advised' WHERE `Applicant_ID`='$Applicant_ID'"); $result = mysqli_query($dbhandle, $query) or die(mysqli_error($dbhandle)); if($result){ echo "Success!"; } else{ echo "Error."; } // successfully insert data into database, displays message "Successful". if($query){ echo "Successful"; } else { echo "Data not Submitted"; } //closing the connection mysqli_close($dbhandle) ?> Ok this is puzzleing. I am geting "Could not delete data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1". but its is deleting the entry that needs to be removed. The "1" is the entry. Just not sure what is causing the error. I do have another delete php but I have put that on the back burning for the time being.
<?php $con = mysqli_connect("localhost","user","password","part_inventory"); // Check connection if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $result = mysqli_query($con, "SELECT * FROM amp20 "); $amp20ptid = $_POST['amp20ptid']; // escape variables for security $amp20ptid = mysqli_real_escape_string($con, $_POST['amp20ptid']); mysqli_query($con, "DELETE FROM amp20 WHERE amp20ptid = '$amp20ptid'"); if (!mysqli_query($con, $amp20ptid)); { die('Could not delete data: ' . mysqli_error($con)); } echo "Part has been deleted to the database!!!\n"; mysqli_close($con); } ?> This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=359592.0 I'm doing some work with the Discogs API trying to serialize the data of a release for use in another local application. A release on Discogs is something like a music album, so it contains the tracklisting, artists, remixers etc. Here is a sample track row returned from the API (xml) Code: [Select] <track> <artists> <artist> <name>Ramirez</name> <join>And</join> </artist> <artist> <name>Tajada</name> </artist> </artists> <title>Listen To The Drums</title> <duration>8:10</duration> </track> Which more simply looks like this: Ramirez And Tajada - Listen To The Drums On this, I need to class the artist "Tajada" as a guest on this track, however, the "role" is defined in the previous artist's XML row: Code: [Select] <name>Ramirez</name> <join>And</join> How can I sort through the rows to 'swap' these around? Ideally it would look like this: Code: [Select] <track> <artists> <artist> <name>Ramirez</name> </artist> <artist> <name>Tajada</name> <join>And</join> </artist> </artists> <title>Listen To The Drums</title> <duration>8:10</duration> </track> Thanks for any help. Hello, I will tell you whant I want to do first and what I've done so far and hopefuly someone will be able to help. What I hope for is to have one unique index.php that will work everywhere. I don't mind if I have to modify each and add path where it is located since this won't happen often. It needs to take car of preferred language and if someone land in a directory, I want it to load the index.php there. I also look to not expose hidden URL in the browser URL box. See *note 1 below. My directory structure is as follow: /index.php /about/index.php /blahblah/index.php The current index.php I'm trying to build looks like this: <?php if (preg_match('/^www.(.+)$/i', $_SERVER['HTTP_HOST'], $matches)) { header("Status: 301 Move permanently", false, 301); header('Location: http://'.$matches[1].$_SERVER['REQUEST_URI']); exit; } session_start(); $Lang = $_SESSION['lang']; if (!isset($Lang)) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $Lang = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']); $Lang = strtolower(substr(chop($Lang[0]),0,2)); if ($Lang !== 'fr' && $Lang !== 'en') { $Lang = "en"; } } else { $Lang = "en"; } $_SESSION['lang'] = $Lang; } include $_SERVER["DOCUMENT_ROOT"] . ("/index_" . $_SESSION['lang'] . ".php"); ?> First I remove "www." in the address when applies. Not a must but I like that. Then I check if Language is already set, if not I detect and set it for next pages. I finally load the proper page according to language with an "include" so index_en.php remain secret (sort of). *note 1: all my index_xx.php pages in every directory have this: Code: [Select] <script language="javascript" type="text/javascript"> if (self == top) top.location.href="directory/index.php"; </script> When in the root, it seems to work and I get the proper page but if I place this in /about/ then when I tried to load /about/index.php it doesn't work. I think the include on the last line could be the problem. I'm either close or far from it, I don't know. Thank you. Hi all i provided a little code to someone in the misc thread to block users based on the user agent language as an alternative to ipaddresses. I used switch for this but the each line is executed even if my language code is different. Anyone have an idea why the switch code below is messing with me? <?php if ( isset( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ) ){ $languages = strtolower( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ); // $languages = ' fr-ch;q=0.3, da, en-us;q=0.8, en;q=0.5, fr;q=0.3'; // need to remove spaces from strings to avoid error $languages = str_replace( ' ', '', $languages ); $languages = explode( ",", $languages ); // do something when you don't like the language switch ($languages[0]) { // first array item case 'ko': // korea echo "do something or set a variable"; break; case 'ru-md'||'ru': // russia echo "do something or set a variable"; break; case 'zh-cn'||'zh-hk'||'zh-mo'||'zh-sg'||'zh-tw'||'zh': // china echo "do something or set a variable"; break; case 'ne': // india echo "do something or set a variable"; break; default: echo "good"; } } ?> I changed it to a different code that uses in_array() which works, but i really would love to know why the above is not working as intended, i looked at php.net, but didn't found something nice in the comments. Maybe a guru out here that knows? <?php if ( isset( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ) ){ $languages = strtolower( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ); // $languages = ' fr-ch;q=0.3, da, en-us;q=0.8, en;q=0.5, fr;q=0.3'; // need to remove spaces from strings to avoid error $languages = str_replace( ' ', '', $languages ); $languages = explode( ",", $languages ); // do something when you don't like the language $lang_array = array('ko','ru-md','ru','zh-cn','zh-hk','zh-mo','zh-sg','zh-tw','zh','ne'); if (in_array($languages[0], $lang_array)){ echo 'bad stuff'; }else{ echo 'good stuff'; } } ?> Thanks guys!! Hi I did not se this in any posts and it seems to be a good script. It was supposed to be in somthing I bought but instaed they just put it in a video. Problem is I am getting an error in the if statement, or at least that is what it is telling me. Anyone know what is wrong with it? Appreciate your help in advance Thanks <?php $siteA ="http://www.yoursite.com/A.html"; $siteB ="http://www.yoursite.com/B.html"; $switchtime = "2011-03-14 06:44:00"; $k = strtotime($switchtime); $t = (int)date('U') /* DEBUG */ //echo date("y-m-d h:i:s T",$k); //echo "<br/>".date("Y-m-d h:i:s T",$t); /* */ if($t<$k) header('location: '.$siteA); else header('location: '.$siteB); ?> Hi guys
I have this code below and all works fine when submitting this online application apart from when someone types either ' # & into one of the comment fields in which it throws up the error. Have tried various fixes from across the internet but no joy. Can anyone offer suggestions?
<?php
$con = mysql_connect("localhost:3306","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('sfapp', $con);
$sql="INSERT INTO 'sfapp' ('surname_add','forename_add','dob_add','hometele_add','mobiletele_add','homeadd_add','siblings_add','schoolname_add','headname_add','schooladd_add','schooltele_add','schoolem_add','alevel_add','personstate_add','nameprovided_add','pe_add','se_add','PredGrade_Art','PredGrade_AScience','PredGrade_BusStudies','PredGrade_Electronics','PredGrade_EnglishLang','PredGrade_EnglishLit','PredGrade_French','PredGrade_German','PredGrade_Geog','PredGrade_Graphics','PredGrade_History','PredGrade_Maths','PredGrade_SepScience','PredGrade_ProductDesign','PredGrade_Spanish','PredGrade_Other','Gender_Male','Gender_Female','Sub_EnglishLit','Sub_Maths','Sub_FurtherMaths','Sub_Biology','Sub_Chemistry','Sub_Physics','Sub_French','Sub_German','Sub_Spanish','Sub_Geography','Sub_History','Sub_RE','Sub_FineArt','Sub_Business','Sub_Computing','Sub_GlobPersp','Sub_DramaAndTheatre','Sub_PE','Sub_Dance','Sub_Politics','Sub_Psychology','Sub_Sociology','readprospect_chk','Sib_Yes','Sib_No','Current_Student_Yes','Current_Student_No','I_Understand_chk','Current_Education_chk','Local_Care_chk','Staff_Cwhls_chk','Sub_Film')
VALUES
('$_POST[surname_add]','$_POST[forename_add]','$_POST[dob_add]','$_POST[hometele_add]','$_POST[mobiletele_add]','$_POST[homeadd_add]','$_POST[siblings_add]','$_POST[schoolname_add]','$_POST[headname_add]','$_POST[schooladd_add]','$_POST[schooltele_add]','$_POST[schoolem_add]','$_POST[alevel_add]','$_POST[personstate_add]','$_POST[nameprovided_add]','$_POST[pe_add]','$_POST[se_add]','$_POST[PredGrade_Art]','$_POST[PredGrade_AScience]','$_POST[PredGrade_BusStudies]','$_POST[PredGrade_Electronics]','$_POST[PredGrade_EnglishLang]','$_POST[PredGrade_EnglishLit]','$_POST[PredGrade_French]','$_POST[PredGrade_German]','$_POST[PredGrade_Geog]','$_POST[PredGrade_Graphics]','$_POST[PredGrade_History]','$_POST[PredGrade_Maths]','$_POST[PredGrade_SepScience]','$_POST[PredGrade_ProductDesign]','$_POST[PredGrade_Spanish]','$_POST[PredGrade_Other]','$_POST[Gender_Male]','$_POST[Gender_Female]','$_POST[Sub_EnglishLit]','$_POST[Sub_Maths]','$_POST[Sub_FurtherMaths]','$_POST[Sub_Biology]','$_POST[Sub_Chemistry]','$_POST[Sub_Physics]','$_POST[Sub_French]','$_POST[Sub_German]','$_POST[Sub_Spanish]','$_POST[Sub_Geography]','$_POST[Sub_History]','$_POST[Sub_RE]','$_POST[Sub_FineArt]','$_POST[Sub_Business]','$_POST[Sub_Computing]','$_POST[Sub_GlobPersp]','$_POST[Sub_DramaAndTheatre]','$_POST[Sub_PE]','$_POST[Sub_Dance]','$_POST[Sub_Politics]','$_POST[Sub_Psychology]','$_POST[Sub_Sociology]','$_POST[readprospect_chk]','$_POST[Sib_Yes]','$_POST[Sib_No]','$_POST[Current_Student_Yes]','$_POST[Current_Student_No]','$_POST[I_Understand_chk]','$_POST[Current_Education_chk]','$_POST[Local_Care_chk]','$_POST[Staff_Cwhls_chk]','$_POST[Sub_Film]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
?>
<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['pe_add'])) {
//Email information
$admin_email = $_REQUEST['pe_add'];
$forename = $_REQUEST['forename_add'];
$email = "autoreply@testing.com";
$subject = "Application";
$desc =
"Dear $forename
Thank you for submitting your online application, we will be in touch shortly.
"
;
//send email
mail($admin_email, "$subject", "$desc", "From:" . $email);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
If you are seeing this, you need to go back and fill out the Personal Email section!
<?php
}
header("location:complete.php");
mysql_close($con)
?>
Thanks in advance.
Can anyone help me with this - I don't normally do coding.
I've just moved an old site onto new hosting and I'm getting this message: Deprecated: Function ereg_replace() is deprecated
The code looks like this:
if( preg_match( '/sl/i', $sOption ) )
$sContent = addslashes( $sContent );
else
$sContent = stripslashes( $sContent );
$sContent = ereg_replace( "\r", '', $sContent );
if( preg_match( '/len/i', $sOption ) )
$sContent = checkLengthOfTxt( $sContent );
I changed it to look like this:
if( preg_match( '/sl/i', $sOption ) )
$sContent = addslashes( $sContent );
else
$sContent = stripslashes( $sContent );
$sContent = preg_replace( "\r", '', $sContent );
if( preg_match( '/len/i', $sOption ) )
$sContent = checkLengthOfTxt( $sContent );
But now get this warning message:
Warning: preg_replace() [function.preg-replace]: Empty regular expression
I didn't build the site so I don't even know what the script is trying to do - forgive my ignorance!
How to solve this error out PHP Deprecated: Function ereg_replace() is deprecated in using this code Code: [Select] $shoutcast_on_off =''; $scsuccs = ''; $listenlink = ''.$scdef.''; $scfp = fsockopen("$scip", $scport, &$errno, &$errstr, 30); if(!$scfp) { $scsuccs=1; } $page = ''; if($scsuccs!=1){ fputs($scfp,"GET /admin.cgi?pass=$scpass&mode=viewxml HTTP/1.0\r\nUser-Agent: SHOUTcast Song Status (Mozilla Compatible)\r\n\r\n"); while(!feof($scfp)) { $page .= fgets($scfp, 1000); } $loop = array("STREAMSTATUS"); $y=0; while($loop[$y]!=''){ $pageed = ereg_replace(".*<$loop[$y]>", "", $page); $scphp = strtolower($loop[$y]); $$scphp = ereg_replace("</$loop[$y]>.*", "", $pageed); $y++; } fclose($scfp); } $online1 = ''; if ($streamstatus == "1") { $online1 = '<center><img src="'.$BASEURL.'/styles/'.$theme.'/theme_images/DJ.png" border="0" height="150"></center><br> <center><a href="'.$BASEURL.':'.$scport.'/listen.pls"><img src="'.$BASEURL.'/styles/'.$theme.'/theme_images/klausom.png" width="150px" height="auto"></a></center>'; } else { $online2 = ''; $online2 = '<center><img src="'.$BASEURL.'/styles/'.$theme.'/theme_images/off.png" border="0" height="150"></center>'; } // BEGIN Plugin: shoutcast_on_off $shoutcast_on_off = $online1.$online2; // END Plugin: shoutcast_on_off eval("\$shoutcast = \"".$TSUE['TSUE_Template']->LoadTemplate('shoutcast')."\";"); return $shoutcast; Hi.. I create mysql syntax for query testing before i input to my php code here is my mysql code: Code: [Select] set @t = 0; set @rqty=31968; SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN @t+OUTPUT_QTY > @rqty THEN @rqty -@t ELSE OUTPUT_QTY END as qty, @t := @t + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = 'P28' AND (@t < @rqty); and i attach the sample output of the above query. Now that query test is work i will input that code to my php codes. $sql = "SELECT SKUCode, Materials, Comp, Qty FROM bom WHERE SKUCode = '$SKUCode'"; $res = mysql_query($sql, $con); ($row = mysql_fetch_assoc($res)); $Materials = $row['Materials']; $Qty = $row['Qty']; $Comp = $row['Comp']; //P28 //-----Compute Req Qty and Save to table---// $ReqQty = $Qty * $POReq; // 31968 $sql = "UPDATE bom SET ReqQty = '$ReqQty' WHERE SKUCode = '$SKUCode' AND Materials = '$Materials'"; $resReqQty = mysql_query($sql, $con); $t = 0; $sql = "SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN $t+OUTPUT_QTY > $ReqQty THEN $ReqQty -$t ELSE OUTPUT_QTY END as qty, $t := $t + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = '$Comp' AND ($t < $ReqQty)"; when I echo the query: I got this: SELECT LOT_CODE as code, DATE_ENTRY, CASE WHEN 0+OUTPUT_QTY > 31968 THEN 31968 -0 ELSE OUTPUT_QTY END as qty, 0 := 0 + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = 'P28' AND (0 < 31968) then I run it to the sql and I got an error: Error Code : 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= 0 + d.OUTPUT_QTY as cumulative FROM dipping d WHERE SUBSTR(LOT_CODE, 9,4) = '' at line 1 (0 ms taken) Any help is highly appreciated Thank you so much I'm pretty new to this, How exactly could i get the text between the www. and .com? so if i have a url: http://www.facebook.com I want to just return "facebook" i'm trying to grab the file name from mediafire to my database caption, I have rapidshare working fine. here's the code for rapidshare Code: [Select] if($type==1) { $words=$links[$j]; preg_match("/rapidshare\.com\/files\/\d+\/(.+)/",$words,$match); unset($words); $words=$match[1]; unset($match); $words=preg_split("/[_\.\-]/",$words); $lastword=array_pop($words); if($lastword=="html") array_pop($words); $words=implode(" ",$words); $words=preg_replace("/\s{2,}/"," ",$words); $caption=mysql_real_escape_string($words); unset($words); }How ever, i'm not sure which preg_match would be the correct one for mediafire.. appreciate any help. How to a check if a php variable value is one of the following characters: A to J, or ,k to t, (ie.: A B C D E F G H I J k l m n o p q r s t)
I tried:
if (preg_match[A-Jk-t], $checkChar) { // do this } im trying to make a script so i can get users details like longitude, latitude etc
but im having trouble matching the html by regular expression
here is the html below that im trying to extract the data from:
any help or possible any alternative, suggested ways would be greatful thank you
<td>Country:</td> <td><img src="/images/dot.gif" class="flag-16 gb" align="absmiddle" width="16" height="16" title="United Kingdom"> United Kingdom (GB)</td> </tr> <tr> <td>City:</td> <td>Newport</td> </tr> <tr> <td>Region:</td> <td>Newport</td> </tr> <tr> <td>Latitude:</td> <td>51.5833</td> </tr> <tr> <td>Longitude:</td> <td>-2.9833</td> </tr> <tr> <td>Timezone:</td> <td>Europe/London</td> <?php $url = "http://smart-ip.net/geoip/2.101.108.124/"; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $rawdata = curl_exec($ch); curl_close($ch); if (preg_match('/<td>Country:</td><td>[img](?P<country>\w+)</td>/$', $rawdata, $match)) { $country = $match['country']; } if (preg_match('/<td>City:</td><td>(?P<city>\w+)</td>/$', $rawdata, $match)) { $city = $match['city']; } if (preg_match('/<td>Region:</td><td>(?P<region>\w+)</td>/$', $rawdata, $match)) { $region = $match['region']; } if (preg_match('/<td>Latitude:</td><td>(?P<latitude>\d+)</td>/$', $rawdata, $match)) { $latitude = $match['latitude']; } if (preg_match('/<td>Longitude:</td><td>(?P<longitude>\d+)</td>/$', $rawdata, $match)) { $longitude = $match['longitude']; } if (preg_match('/<td>Timezone:</td><td>(?P<timezone>\w+)</td>/$', $rawdata, $match)) { $timezone = $match['timezone']; } ?> |