php regex failed, why? - php

The value is AbcDefg_123.
Here is the regex:
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
Should allow a-zA-Z0-9.:_-/ and space in any order or format and does need all but at least one character.
EDIT: Sorry again, looks like var_dump() is my new best friend. I'm working with XML and it's passing the tag as well as the value.
#SilentGhost thnx for the tips.

It works for me too.
<?php
class RegexValidator
{
public function IsAlphaNumeric($alphanumeric)
{
return preg_match('/^[\w. \/:_-]+$/', $alphanumeric);
}
}
?>
and this is how I am testing it.
<?php
require_once('Classes/Utility.php');
$regexVal = new RegexValidator();
$list = array("abcd", "009aaa", "%%%%", "0000(", "aaaa7775aaa", "$$$$0099aaa", "kkdkdk", "aaaaa", "..0000", " ");
foreach($list as $value)
{
if($regexVal->IsAlphaNumeric($value))
{
echo $value . " ------>passed";
echo "<BR>";
}
else
{
echo $value . "------>failed";
echo "<br>";
}
}
?>

function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[A-Za-z0-9\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
print checkAlphNum("AbcDefg_123");
Returns true.

Related

string replace without using any in-built function

With a program to replace substring in a string without using str_replace
should be generic function should work for below example:
Word : Hello world
Replace word : llo
Replace by : zz
Output should be: Hezz world
Word : Hello world
Replace word : o
Replace by : xx
Output should be: Hellxx wxxrld
This is what i wrote to solve it
function stringreplace($str, $stringtoreplace, $stringreplaceby){
$i=0;$add='';
while($str[$i] != ''){
$add .= $str[$i];
$j=0;$m=$i;$l=$i;$check=0;
if($str[$i] == $stringtoreplace[$j]){
while($stringtoreplace[$j] != ''){
if($str[$m] == $stringtoreplace[$j]){
$check++;
}
$j++;$m++;
}
if($check == strlen($stringtoreplace)){
$n=0;$sub='';
for($n=0;$n<=strlen($stringtoreplace);$n++){
$str[$l] = '';
$sub .= $str[$l];
$l++;
}
$add .= $stringreplaceby;
$i += $check;
}
}
$i++;
}//echo $add;exit;
return $add;
}
I am getting output as helzzworld .
Please take a look what I did wrong or if you have better solution for this please suggest.
You can do this by explode the main string into array then implode your stringreplaceby to your array parts creating new string
<?php
function stringreplce($str,$strreplace,$strreplaceby){
$str_array=explode($strreplace,$str);
$newstr=implode($strreplaceby,$str_array);
return $newstr;
}
echo stringreplce("Hello World","llo","zz")."<br>";
echo stringreplce("Hello World","Hel","zz")."<br>";
echo stringreplce("Hello World"," Wo","zz")."<br>";
echo stringreplce("Hello World","rl","zz")."<br>";
echo stringreplce("Hello World","ld","zz")."<br>";
?>
Try this simplest one, without using str_replace, Here we are using explode and implode and substr_count.
1. substr_count for counting and checking the existence of substring.
2. explode for exploding string into array on the basis of matched substring.
3. implode joining the string with replacement.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
if(substr_count($string, $toReplace))
{
$array=explode($toReplace,$string);
return implode($replacement, $array);
}
}
Solution 2:
Try this code snippet here not best, but working
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
while($indexArray=checkSubStringIndexes($toReplace,$string))
{
$stringArray= getChars($string);
$replaced=false;
$newString="";
foreach($stringArray as $key => $value)
{
if(!$replaced && in_array($key,$indexArray))
{
$newString=$newString.$replacement;
$replaced=true;
}
elseif(!in_array($key,$indexArray))
{
$newString=$newString.$value;
}
}
$string=$newString;
}
return $string;
}
function getLength($string)
{
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$counter++;
}
else
{
break;
}
}
return $counter;
}
function getChars($string)
{
$result=array();
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$result[]=$string[$counter];
$counter++;
}
else
{
break;
}
}
return $result;
}
function checkSubStringIndexes($toReplace,$string)
{
$counter=0;
$indexArray=array();
$newCounter=0;
$length= getLength($string);
$toReplacelength= getLength($toReplace);
$mainCharacters= getChars($string);
$toReplaceCharacters= getChars($toReplace);
for($x=0;$x<$length;$x++)
{
if($mainCharacters[$x]==$toReplaceCharacters[0])
{
for($y=0;$y<$toReplacelength;$y++)
{
if(isset($mainCharacters[$x+$y]) && $mainCharacters[$x+$y]==$toReplaceCharacters[$y])
{
$indexArray[]=$x+$y;
$newCounter++;
}
}
if($newCounter==$toReplacelength)
{
return $indexArray;
}
}
}
}
function ganti_kata($kata,$kata_awal,$kata_ganti){
$i =0; $hasil;
$panjang = strlen($kata);
while ($i < $panjang) {
if ($kata[$i] == $kata_awal) {
$hasil[$i] = $kata_ganti;
echo $hasil[$i];
}
else if ($kata[$i] !== $kata_awal){
$hasil[$i] = $kata[$i];
echo $hasil[$i];
}
$i++;
}
}
echo ganti_kata('Riowaldy Indrawan','a','x');
This code using php

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

Return a value properly from a tree with recursion [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
This is my code
https://eval.in/157357
You can use a json parser if you wanna see the tree. This tree is returned by the Magento SOAP Api.
http://www.magentocommerce.com/api/soap/catalog/catalogCategory/catalog_category.tree.html
<?php
function getCategoryId($tree,$needle,&$val)
{
if(!empty($tree["name"]) && $tree["name"] === $needle)
{
$val = $tree["category_id"];
return $tree["category_id"];
}
else
{
if(isset($tree["children"]["category_id"]))
{
getCategoryId($tree["children"],$needle,$val);
}
else
{
foreach ($tree["children"] as $child) {
getCategoryId($child,$needle,$val);
}
}
}
}
function main()
{
$testjson = <<<EOL
{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"catroot","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"cat1","is_active":"1","position":"1","level":"2","children":[{"category_id":"7","parent_id":"3","name":"cat11","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"8","parent_id":"3","name":"cat12","is_active":"0","position":"2","level":"3","children":[]}]},{"category_id":"9","parent_id":"2","name":"cat2","is_active":"0","position":"2","level":"2","children":[{"category_id":"11","parent_id":"9","name":"cat21","is_active":"0","position":"1","level":"3","children":[{"category_id":"12","parent_id":"11","name":"cat211","is_active":"0","position":"1","level":"4","children":[]},{"category_id":"13","parent_id":"11","name":"cat212","is_active":"0","position":"2","level":"4","children":[]}]}]},{"category_id":"10","parent_id":"2","name":"cat3","is_active":"0","position":"3","level":"2","children":[{"category_id":"14","parent_id":"10","name":"cat31","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"15","parent_id":"10","name":"cat32","is_active":"0","position":"2","level":"3","children":[{"category_id":"16","parent_id":"15","name":"cat321","is_active":"0","position":"1","level":"4","children":[{"category_id":"17","parent_id":"16","name":"cat3211","is_active":"0","position":"1","level":"5","children":[]}]}]}]}]}]}
EOL;
$result = (json_decode($testjson,true));
$res = getCategoryId($result,"cat211",$val);
var_dump($res);
var_dump($val);
}
main();
?>
Why my function getCategoryId return NULL ? I don't want use the reference $val that was juste for testing.
You need to return the result from the recursive calls:
<?php
function getCategoryId($tree,$needle,&$val)
{
if(!empty($tree["name"]) && $tree["name"] === $needle)
{
//var_dump($tree);
//var_dump($tree["category_id"]);
$val = $tree["category_id"];
return $tree["category_id"];
}
else
{
if(isset($tree["children"]["category_id"]))
{
return getCategoryId($tree["children"],$needle,$val);
}
else
{
foreach ($tree["children"] as $child) {
$return = getCategoryId($child,$needle,$val);
if($return){
return $return;
}
}
}
}
}
function main()
{
$testjson = <<<EOL
{"category_id":"1","parent_id":"0","name":"Root Catalog","is_active":null,"position":"0","level":"0","children":[{"category_id":"2","parent_id":"1","name":"catroot","is_active":"1","position":"1","level":"1","children":[{"category_id":"3","parent_id":"2","name":"cat1","is_active":"1","position":"1","level":"2","children":[{"category_id":"7","parent_id":"3","name":"cat11","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"8","parent_id":"3","name":"cat12","is_active":"0","position":"2","level":"3","children":[]}]},{"category_id":"9","parent_id":"2","name":"cat2","is_active":"0","position":"2","level":"2","children":[{"category_id":"11","parent_id":"9","name":"cat21","is_active":"0","position":"1","level":"3","children":[{"category_id":"12","parent_id":"11","name":"cat211","is_active":"0","position":"1","level":"4","children":[]},{"category_id":"13","parent_id":"11","name":"cat212","is_active":"0","position":"2","level":"4","children":[]}]}]},{"category_id":"10","parent_id":"2","name":"cat3","is_active":"0","position":"3","level":"2","children":[{"category_id":"14","parent_id":"10","name":"cat31","is_active":"0","position":"1","level":"3","children":[]},{"category_id":"15","parent_id":"10","name":"cat32","is_active":"0","position":"2","level":"3","children":[{"category_id":"16","parent_id":"15","name":"cat321","is_active":"0","position":"1","level":"4","children":[{"category_id":"17","parent_id":"16","name":"cat3211","is_active":"0","position":"1","level":"5","children":[]}]}]}]}]}]}
EOL;
$result = (json_decode($testjson,true));
$res = getCategoryId($result,"cat211",$val);
var_dump($res);
var_dump($val);
}
main();
?>

Change php code with function

I have a problem with a piece of code. This code works fine. No problem.
include ("CCheckMail.php");
$checkmail = new CCheckMail ();
$emails = array ("korkula#iservicesmail.com");
foreach ($emails as $email)
{
if ($checkmail->execute ($email)) { return 1; } else { return 0; }
}// end foreach
And now, I want to change to instead use array, I want to send the email to check by var, like this:
include ("CCheckMail.php");
funtion_name($email){
$checkmail = new CCheckMail ();
if ($checkmail->execute ($email)) { return 1; } else { return 0; }
}
} //end function
The new code doesnt work I dont understand why.
Can anyone help me?
Thanks!
Try declaring the object once and reusing it by passing it into the function as well as the email address you're checking.
//Call the checkMail class
include("CCheckMail.php");
//Define the object to work with
$checkmail = new CCheckMail();
//Function to send the emails and return response
function checkEmailFunc($email, $emailObject){
if ($emailObject->execute ($email)) { return 1; } else { return 0; }
}
//Test it out
$emails = array("korkula#iservicesmail.com", "test#example.com");
foreach ($emails as $email) {
if (checkEmailFunc($email, $checkmail)) {
echo "Success! Checked " . $email . "<br/>";
} else {
echo "Failed to check " . $email . "<br/>";
}
}

Get return values of code with tokenizer

I'm trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.
Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.
For example for this piece of code:
<?php
class Bla {
public function Test1()
{
$t = true;
if($t) {
return 1;
}
return 0;
}
public function Test2()
{
echo "bbb";
return; // nothing is returned
}
public function Test3()
{
echo "ccc";
$someval1 = 1;
$someval2 = 2;
return ($someval + $otherval)*2;
}
}
?>
I'm using get_token_all() to identify where a return is done:
$newStr = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{
if (is_array($token))
{
if (($token[0] == $returnToken))
{
// found return, now get what is returned?
}
else
{
$token = $token[1];
}
}
$newStr .= $token;
}
I have no clue how to get the piece of code that is actually returned. That is what i want to get.
Anyone any idea how i could do this?
Perhaps this might help. Though I curious to know what you are ultimately trying to do.
$tokens = token_get_all($str);
$returnCode = '';
$returnCodes = array();
foreach ($tokens as $token) {
// If return statement start collecting code.
if (is_array($tokens) && $token['0'] == T_RETURN) {
$returnCode .= $token[1];
continue;
}
// if we started collecting code keep collecting.
if (!empty($returnCode)) {
// if we get to a semi-colon stop collecting code
if ($token === ';') {
$returnCodes[] = substr($returnCode, 6);
$returnCode = '';
} else {
$returnCode .= isset($token[1]) ? $token[1] : $token;
}
}
}

Categories