PHP Regular expression with arrows (>>) - php

I need a little help with my regular expression.
Here is what I've got:
function formatLink($post) {
if(preg_match('/^\>\>[0-9]{+}$/', $post)) {
return "<font color=\"red\">".$post."</font>";
} else {
return "<font color=\"#b7b7b7\">".$post."</font>";
}
}
echo formatLink(">>86721678");
And honestly I don't know what doesn't it work. It should work for any string like this:
>>1
>>87759
Very similar to imageboard-like post ref.

Remove the curly braces. They are not needed. You also need to add the m modifier to allow it to match on any line, not just the entire post.
Also note that this will only work if there is literally nothing else on the line, not even a space. You might want to relax it like so:
/^\s*>>\s*\d+\s*$/m

You forgot to escape!
<?php
function formatLink($post) {
if(preg_match('/^\>\>[0-9]{+}$/', $post))
{
return "<font color=\"red\">".htmlentities($post)."</font>";
}
else
{
return "<font color=\"#b7b7b7\">".htmlentities($post)."</font>";
}
}
echo formatLink(">>86721678");
Running example.

I think your problem is in your regular expression.
Use this instead:
if(preg_match('/^\>\>([0-9]+)$/', $post)) {
See that I removed the curly brackets from your regular expression.

Try changing the regex to
/^\>\>[0-9]*$/

Related

php bbcode preg match all

I am trying to write a function which will be checked the open bbcode tags and the close bbcode tags.
Here is what I have write so far:
public function CheckBBCodes($argText)
{
$openQuoteTagCounter = preg_match_all('[quote]', $argText, $openQuoteTagCounter);
$closeQuoteTagCounter = preg_match_all('#\[\/quote\]\s*#', $argText, $closeQuoteTagCounter);
if($openQuoteTagCounter > $closeQuoteTagCounter)
{
echo "There are more open quote tags than close quote tags!";
}
if($closeQuoteTagCounter > $openQuoteTagCounter)
{
echo "There are more close quote tags than open quote tags!";
}
}
It doesn't work. What am I forgetting?
Regex
What stands out most is your regex patterns are incorrect...
This:
$openQuoteTagCounter = preg_match_all('[quote]', $argText, $openQuoteTagCounter);
$closeQuoteTagCounter = preg_match_all('#\[\/quote\]\s*#', $argText, $closeQuoteTagCounter);
Should be:
$openQuoteTagCounter = preg_match_all('#\[quote\]#i', $argText, $openQuoteTagCounter);
$closeQuoteTagCounter = preg_match_all('#\[/quote\]#i', $argText, $closeQuoteTagCounter);
Which could be further improved:
$openQuoteTagCounter = preg_match_all('#\[quote\]#i', $argText);
$closeQuoteTagCounter = preg_match_all('#\[/quote\]#i', $argText);
The i is used to make it case insensitive in case you have tags like [QUOTE].
You don't need to escape forward slashes (/) because you're using # as a delimiter.
You don't need the third argument in the preg_match_all because you aren't doing anything with it and you're overwriting it anyway...
IF(..)
I also suggest that you use the following code structure
if(X > Y){
//Do stuff...
}
else if(Y > X){
//Do other stuff...
}
else{
//Do different stuff...
}
as opposed to if(...){...} if(...){...} if(...){...} if(...){...}

Regex to get a specific function code from php file

I'm editing a PHP file to replace a function's code by another code provided.
My problem is that the function's code may change. So, I don't know exactly how I should do the regex to find it.
Here's an example:
function lol()
{
echo('omg');
$num=0;
while($num<100)
{
echo('ok');
}
}
function teste()
{
echo('ola');
while($num<100)
{
echo('ok');
}
}
function test()
{
echo('oi');
while($num<100)
{
echo('ok');
}
}
What I need is to get the code of function teste(), which would be:
echo('ola');
while($num<100)
{
echo('ok');
}
BUT: I do not know how many whiles, foreaches or how many brackets are inside the functions, neither I don't know it's order. The example was just an example.
How would I be able to get the function's code?
Thank you in advance.
Disclaimer
As other users stated, this is probably not a good approach. And if you decided to use it anyway, double-check your result as regex can be treacherous.
Ugly solution
You can you something like to match even if the function is the last one (#Nippey):
(?:function teste\(\))[^{]*{(.*?)}[^}]*?(?:function|\Z)
Note: I'm using (?:xyz) which is for non-capturing parentheses group. Check if your regex engine support it.
Output
echo('ola');
while($num<100)
{
echo('ok');
}
Using recursive pattern (?R) you can match nested brackets:
$result = preg_replace_callback('#(.*?)\{((?:[^{}]|(?R))*)\}|.*#si', function($m){
if(isset($m[1], $m[2]) && preg_match('#function\s+teste\b#i', $m[1])){
return $m[2];
}
}, $code); // Anonymous function is used here which means PHP 5.3 is required
echo $result;
Online demo

Use preg_match to find word in URL (or string with no spaces)

Sorry I'm kinda new to regex, anyways I have a url like http://example.com/test/folder/?get=ThisisaValue and I need it to return whether the word "get" is in there or not.
Whenever I run the function I get no match? Any help is appreciated thank you.
Sample code, let's say $_SERVER['HTTP_REFERER'] is http://example.com/hello/?state=12345
if(preg_match("state", $_SERVER['HTTP_REFERER'])) {
echo "match";
} else {
echo "no match";
}
I need it to return whether the word "get" is in there or not
In that case you don't need to match anything - you can just check for whether the substring is in the string, using strpos().
if (strpos($url, 'get')) {
// do something
}
you are forgetting the delimiters:
preg_match("~state~", $_SERVER['HTTP_REFERER'])
now it should work :)

preg_match multiple expressions

hi guys i was wondering how could i build e regExp that says:
"this string may contain 1-25 letters that are not these specific words:"root","bin","download","shutdown"
So I thought:
$dang_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,$field) || !preg_match($dang_words,$field))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
But it's not working
why?
thanks
Luca
$dangerous_words="/(root)|(bin)|(shutdown)|(download)/";
$reg_exp="/^[a-z]{1,25}$/";
if(preg_match($reg_exp,strtolower(trim($field))) && !preg_match($dangerous_words,strtolower(trim($field))))
{
echo "your input it's okkk!";
}
else
echo "this is a bad word!!";
You have your logical operators messed up.. Just changed from || to &&.
Close... Try this:
/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/
It uses a forward assertion
So, it becomes:
if (preg_match('/^(?!.*(root|bin|shutdown|download))[a-z]{1,25}$/', $content)) {
echo "Your input is ok";
} else {
echo "there is a bad word/invalid content";
}
I think your issue lies with all the ( ). In some old code I created a while ago I used this:
$stopInjectionVerbs = "/(alter|begin|cast|convert|create|cursor|declare|delete|drop|end|exec|fetch|insert|kill|open|select|sys|table|update)/";
$errors = array();
if (preg_match($stopInjectionVerbs, $select)) {
$errors[] = "Can not use SQL injection Strings";
}
This all works correctly. Have a go without the brackets around each individual word.

Determine if a character is alphabetic

Having problems with this.
Let's say I have a parameter composed of a single character and I only want to accept alphabetic characters. How will I determine that the parameter passed is a member of the latin alphabet (a–z)?
By the way Im using PHP Kohana 3.
Thanks.
http://php.net/manual/en/function.ctype-alpha.php
<?php
$ch = 'a';
if (ctype_alpha($ch)) {
// Accept
} else {
// Reject
}
This also takes locale into account if you set it correctly.
EDIT: To be complete, other posters here seem to think that you need to ensure the parameter is a single character, or else the parameter is invalid. To check the length of a string, you can use strlen(). If strlen() returns any non-1 number, then you can reject the parameter, too.
As it stands, your question at the time of answering, conveys that you have a single character parameter somewhere and you want to check that it is alphabetical. I have provided a general purpose solution that does this, and is locale friendly too.
Use the following guard clause at the top of your method:
if (!preg_match("/^[a-z]$/", $param)) {
// throw an Exception...
}
If you want to allow upper case letters too, change the regular expression accordingly:
if (!preg_match("/^[a-zA-Z]$/", $param)) {
// throw an Exception...
}
Another way to support case insensitivity is to use the /i case insensitivity modifier:
if (!preg_match("/^[a-z]$/i", $param)) {
// throw an Exception...
}
preg_match('/^[a-zA-Z]$/', $var_vhar);
Method will return int value: for no match returns 0 and for matches returns 1.
I'd use ctype, as Nick suggested,since it is not only faster than regex, it is even faster than most of the string functions built into PHP. But you also need to make sure it is a single character:
if (ctype_alpha($ch) && strlen($ch) == 1) {
// Accept
} else {
// Reject
}
You can't use [a-zA-Z] for Unicode.
here are the example working with Unicode,
if ( preg_match('/^\p{L}+$/u', 'my text') ) {
echo 'match';
} else {
echo 'not match';
}
This will help hopefully.This a simple function in php called ctype_alpha
$mystring = 'a'
if (ctype_alpha($mystring))
{
//Then do the code here.
}
You can try:
preg_match('/^[a-zA-Z]$/',$input_char);
The return value of the above function is true if the $input_char contains a single alphabet, else it is false. You can suitably make use of return value.

Categories