I have to match php variable in php file - php

I have to match php variable in the php file using preg_match()
$GLOBALS['app_list_strings']['enjay_host_list'] = array (
How can I do this.
I am doing,
<?php
$filename='/var/www/su/custom/include/language/en_us.lang.php';
$fileopen=file($filename);
//echo $fileopen[2];
$NoOflines = count($fileopen);
echo $NoOflines ."<br>";
$Changed=0;
$Foundon=0;
$FoundFirstClose=0;
for($i=0;$i<$NoOflines;$i++)
{
echo $fileopen[$i]."<br>";
if(preg_match("/\$GLOBALS['app_list_strings']['enjay_host_list']=array ( /i", $fileopen[$i]))
{
$Foundon=$i;
echo $fileopen[$i]."<br>";
}
}
?>

You need to escape every character that has a special meaning in a regexp, which means not only the $ but also [, ] and (. See the PCRE documentation for the list of special characters in pcre regexp.
Another issue is that because you use double quotes, php tries to replace $GLOBALS.. with a variable content unless you double backslash it on top of it, so it's better to just use the Nowdoc syntax (if you use php >= 5.3, which you really should).
$pattern = <<<'EOS'
/\$GLOBALS\['app_list_strings'\]\['enjay_host_list'\]=array \( /i
EOS;
for($i=0;$i<$NoOflines;$i++)
{
echo $fileopen[$i]."<br>";
if(preg_match($pattern, $fileopen[$i]))
{
$Foundon=$i;
echo $fileopen[$i]."<br>";
}
}

your missing some escape characters in your regular expression.
"/\$GLOBALS\['app_list_strings'\]\['enjay_host_list'\]=array\s\(/i"

$string = "\$GLOBALS['app_list_strings']['enjay_host_list']=array (" ;
$match = preg_match("/\\\$GLOBALS\['app\_list\_strings'\]\['enjay\_host\_list'\]\s*=\s*array\s*\(/i", $string);
var_dump($match) ;
Possible issues with your regexp:
You have to escape special chars as ([]_$)
You have to double escape $ sign when using double quotes in PHP
Whitespaces are also important. I used \s* which correspons to 0 or more whitespaces.

Related

Dynamically replace part of a condition block with regex

There is a string in format:
else if($rule=='somerule1')
echo '{"s":1,"n":"name surname"}';
else if($rule=='somerule2')
echo '{"s":1,"n":"another text here"}';
...
"s" can have only number, "n" any text.
In input I have $rule value, and I need to remove the else if block that corresponds to this value. I am trying this:
$str = preg_replace("/else if\(\$rule=='$rule'\)\necho '{\"s\":[0-9],\"n\":\".*\"/", "", $str);
where $str is a string, that contains blocks I mentioned above, $rule is a string with rule I need to remove. But the function returns $str without changes.
What do I do wrong?
For example, script to change "s" value to 1 works nice:
$str = preg_replace("/$rule'\)\necho '{\"s\":[0-9]/", $rule."')\necho '{\"s\":1", $str);
So, probably, I am doing mistake with = symbol, or maybe with space, or with .*.
The regex pattern can be much less strict, much simpler, and far easier to read/maintain.
You need to literally match the first line (conditional expression) with the only dynamic component being the $rule variable, then match the entire line that immediately follows it.
Code: (Demo)
$contents = <<<'TEXT'
else if($rule=='somerule1')
echo '{"s":1,"n":"name surname"}';
else if($rule=='somerule2')
echo '{"s":1,"n":"another text here"}';
TEXT;
$rule = "somerule1";
echo preg_replace("~\Qelse if(\$rule=='$rule')\E\R.+~", "", $contents);
Output:
else if($rule=='somerule2')
echo '{"s":1,"n":"another text here"}';
So, what have I done? Here's the official pattern demo.
\Q...\E means "treat everything in between these two metacharacters literally"
Then the only character that needs escaping is the first $, this is not to stop it from being interpreted as a end-of-string metacharacter, but as the start of the $rule variable because the pattern is wrapped in double quotes.
The second occurrence of $rule in the pattern DOES need to be interpreted as the variable so it is not escaped.
The \R is a metacharacter which means \n, \r and \r\n
Finally match all of the next line with the "any character" . with a one or more quantifier (+).
The pattern does not match because you have to use a double escape to match the backslash \\\$.
Apart from that, you are not matching the whole line as this part ".*\" stops at the double quote before }';
$str = 'else if($rule==\'somerule1\')
echo \'{"s":1,"n":"name surname"}\';
else if($rule==\'somerule2\')
echo \'{"s":1,"n":"another text here"}\';';
$rule = "somerule1";
$pattern = "/else if\(\\\$rule=='$rule'\)\necho '{\"s\":\d+,\"n\":\"[^\"]*\"}';/";
$str = preg_replace($pattern, "", $str);
echo $str;
Output
else if($rule=='somerule2')
echo '{"s":1,"n":"another text here"}';
Php demo

Expecting output is not displaying from php code

This is the code:
<?php
$pattern =' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$text = "kdaiuyq7e611422^^$^vbnvcn^vznbsjhf";
$text_split = str_split($text,1);
$data = '';
foreach($text_split as $value){
if (preg_match("/".$value."/", $pattern )){
$data = $data.$value;
}
if (!preg_match('/'.$value.'/', $pattern )){
break;
}
}
echo $data;
?>
Current output:
kdaiuyq7e611422^^$^vbnvcn^vznbsjhf
Expected output:
kdaiuyq7e611422
Please help me editing my code error. In pattern there is no ^ or $. But preg_match is showing matched which is doubtful.
You string $text have ^ which will match the begin of the string $pattern.
So the preg_match('/^/', $pattern) will return true, then the ^ will append to $data.
You should escape the ^ as a raw char, not a special char with preg_match('/\^/', $pattern) by the help of preg_quote() which will escape the special char.
There is no need to split your string up like that, the whole point of a regular expression is you can specify all the conditions within the expression. You can condense your entire code down to this:
$pattern = '/^[[:word:] ]+/';
$text = 'kdaiuyq7e611422^^$^vbnvcn^vznbsjhf';
preg_match($pattern, $text, $matches);
echo $matches[0];
Kris has accurately isolated that escaping in your method is the monkey wrench. This can be solved with preg_quote() or wrapping pattern characters in \Q ... \E (force characters to be interpreted literally).
Slapping that bandaid on your method (as you have done while answering your own question) doesn't help you to see what you should be doing.
I recommend that you do away with the character mask, the str_split(), and the looped calls of preg_match(). Your task can be accomplished far more briefly/efficiently/directly with a single preg_match() call. Here is the clean way that obeys your character mask fully:
Code: (Demo)
$text = "kdaiuyq7e611422^^$^vbnvcn^vznbsjhf";
echo preg_match('/^[a-z\d ]+/i',$text,$out)?$out[0]:'No Match';
Output:
kdaiuyq7e611422
miknik's method was close to this, but it did not maintain 100% accuracy given your question requirements. I'll explain:
[:word:] is a POSIX Character Class (functioning like \w) that represents letters(uppercase and lowercase), numbers, and an underscore. Unfortunately for miknik, the underscore is not in your list of wanted characters, so this renders the pattern slightly inaccurate and may be untrustworthy for your project.

PHP preg_match to allow only numbers,spaces '+' and '-'

I need to check to see if a variable contains anything OTHER than 0-9 and the "-" and the "+" character and the " "(space).
The preg_match I have written does not work. Any help would be appreciated.
<?php
$var="+91 9766554433";
if(preg_match('/[0-9 +\-]/i', $var))
echo $var;
?>
You have to add a * as a quantifier to the whole character class and add anchors to the start and end of the regex: ^ and $ means to match only lines containing nothing but the inner regex from from start to end of line. Also, the i modifier is unnecessary since there is no need for case-insensitivity in this regex.
This should do the work.
if(!preg_match('/^[0-9 +-]*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}
Just negate the character class:
if ( preg_match('/[^0-9 +-]/', $var) )
echo $var;
or add anchors and quantifier:
if ( preg_match('/^[0-9 +-]+$/', $var) )
echo $var;
The case insensitive modifier is not mandatory in your case.
You can try regex101.com to test your regex to match your criteria and then on the left panel, you'll find code generator, which will generate code for PHP, Python, and Javascript.
$re = "/^[\\d\\s\\+\\-]+$/i";
$str = "+91 9766554433";
preg_match($re, $str, $matches);
You can take a look here.
Try see if this works. I haven't gotten around to test it beforehand, so I apologize if it doesn't work.
if(!preg_match('/^[0-9]+.-.+." ".*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}

How to use PHP to search a string for words starting/ending with special regular expression characters?

I am using PHP to find out whether a string, which starts with a special regular expression character, occurs as a word in a text string. This is the PHP code:
$subject = " hello [hello [helloagain ";
$pattern = preg_quote("[hello");
if (preg_match("/\b" . $pattern . "\b/", $subject, $dummy)) {
echo "match";
} else {
echo "no match";
}
The pattern starts with character [, hence, preg_quote() is used to escape it. There is an instance of [hello as a word in the subject so there should be one match, but the above preg_match() returns no match. I think the reason is that in the subject a special character is not recognized as the start or end of a word, but I can’t think of any way round this, any ideas? Thank you.
If I understand the question correctly, you could just use strpos() with a leading space to separate words:
$subject = " hello [hello [helloagain ";
$pattern = " [hello";
if(strpos($subject, $pattern) !== FALSE)
// ...
else
// ...
I think that not using reg-ex here is actually a better method since you are looking for special reg-ex chars, and they do not have to be escaped if you use strpos().
It would take some modification to be right in all cases, but this worked when I tried it.
You are correct that a word boundary will not match between a space and a [ symbol.
Instead of using a word boundary you can explicitly search for spaces (and other separators such as commas and periods if you wish) before and after the word:
if (preg_match("/(\s|^)" . $pattern . "(?=\s|$)/", $subject, $dummy)) {

replace string (variables) php

I have a string like this: foo($bar1, $bar2)
How to I replace each variable with <span>$variable</span> with regexp?
This is my try (not working):
$row['name'] = preg_replace("/\$\w+/S", "<span>$1</span>", $row['name']);
I only want the variables to be replaced and have a span around them, I don't want commas or spaces to be replaced.
What I want is to have my string foo($bar1, $bar2) to be replaced with foo(<span>$bar1</span>, <span>$bar2</span>) ($bar1 and $bar2 are not variables, it's plain text).
Here are some problems I can see:
Since you are using double quotes for the regex,
you need to escape the $ using two \ as \\$.
Alternatively you can just use single
quote and use \$.
You are using $1 in the replacement
but you are not having any group in
the regex. So have ( ) around
\$\w+
So try:
$str = preg_replace('/(\$\w+)/', "<span>$1</span>", $str);
or
$str = preg_replace("/(\\$\w+)/", "<span>$1</span>", $str);
See it.

Categories