This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 3 years ago.
Using php 5.3 - ereg() deprecated...
I'm trying to convert this function (to preg_match), but I don't understand the "pointer"...
function gethostbyaddr_new($ip)
{
$output = `host -W 1 $ip`;
if (ereg('.*pointer ([A-Za-z0-9.-]+)\..*', $output, $regs))
{
return $regs[1];
}
return $ip;
}
pointer is just a bit of text to be matched
when I run host -W 1 I get
4.4.8.8.in-addr.arpa domain name pointer google-public-dns-b.google.com.
So you can use:
function gethostbyaddr_new($ip)
{
$output = `host -W 1 $ip`;
if (preg_match('/.*pointer ([A-Za-z0-9.-]+)\..*/', $output, $regs))
{
return $regs[1];
}
return $ip;
}
the first parameter of ereg is regular expression. So, .*pointer match anything (.*), then the word "pointer" (pointer), then the rest of expression.
Not much to it really. All you need to do is add a marker character to the start and end of the regex string.
Typically a marker character would be a slash (/), but it can be others (tilde ~ is used quite commonly and would work well for you here), as long as it's the same character at the start and end of the string, and doesn't appear within the string (you'd need to escape it with a backslash if it does).
So your code could look like this:
preg_match('~.*pointer ([A-Za-z0-9.-]+)\..*~', $output, $regs)
Note, if you use a slash as your regex marker character, you will need to double-it up, as slash is also an escape character in a PHP string.
In terms of explaining the actual expression:
.* - this is any number of any characters at the start of the string (you could actually leave this off this expression; it won't affect the matching)
pointer - this is looking for the actual word 'pointer' in the string being matched.
([A-Za-z0-9.-]+) - looks for one or more characters which are alpha-numeric or dot or hyphen. In addition, because these are enclosed in brackets, they become a 'matching group', which means that the result of this part of the search ends up in $regs[1].
\..* - looks for a dot character, followed by any number of any characters. As with the begining of the match, the .* can be dropped as it won't affect the matching.
So the whole expression is looking for a string which looks something like this:
blahblahblahpointer blah123-.blah.blahblahblah
and from that, you will get blah123-.blah in $regs[1].
Related
This question already has answers here:
Regular Expression Word Boundary and Special Characters
(3 answers)
Regular expression to stop at first match
(9 answers)
Closed 2 years ago.
If my string is
<?php $str = 'hello world!'; function func_hello($str) { echo $str; }
I want to find the name of any functions in the string
I'm using the code
preg_match_all('%func_.* ?\(%', $c, $matches);
This is a basic example of what I'm doing. In the real world I'm getting results like this
func_check_error($ajax_action_check, array(
func_post('folder') == '/' || func_post(
func_check_error($fvar_ajax_action_check, array(
Whereas I want the result to be
func_check_error(
func_post(
func_check_error(
I've tried \b to set a boundary but it's not working. i.e.
preg_match_all('%\bfunc_.* ?\(\b%', $c, $matches);
The .* capture the opening parenthesis, and then the first parenthesis (after the function name) is captured, because there is the following parenthesis (the one of the array) which correspond to the \( of your pattern.
You should try a more restrictive condition on the function name, such as alphanumeric only or anything but a parenthesis, maybe replace the func_.* by func_[^(]* wich will stop at the first parenthesis match
Simple regex should work fine:
~func_.*\(~
If this is not giving the results you expect, it may be due to another issue with your code and how you're using the regex.
This question already has answers here:
How do I replace certain parts of my string?
(5 answers)
Closed 2 years ago.
I'm creating a simple comment system connected by Steam API. Every Steam user connected in my website can automatically post things. But i'm changing some functions to replace things like the URLs.
My question is: When a user post something like,
"Hello I'm nice, have a look at http://www.cute.com"
Automatically replaces the http:// for the link without changing the http:// in the string.
Maybe something like this?
<?php
$str = "helloo im nice, have a look http://www.cute.com";
echo preg_replace("/http:\/\/(.+)\.(.+)\.(.+)/", "<a href='http://$1.$2.$3'>$1.$2.$3</a>", $str);
?>
This will convert any link into an anchor (or an a tag).
Alternative added
Alternatively, it might be a good idea to add support for https as well. In which case the following might be useful.
<?php
$str = "helloo im nice, have a look http://www.cute.com";
echo preg_replace("/http(s?):\/\/(.+)\.(.+)\.(.+)/", "<a href='http$1://$2.$3.$4'>http$1://$2.$3.$4</a>", $str);
?>
This takes advantage of the ? modifier which means "one or more of the preceding character". In this case it is the "s" character since it is "http" and "https" both match.
Explanation
This uses RegEx (or Regular Expressions) to create this.
The first parameter of the preg_replace function takes the RegEx (I like to test mine here: http://regexr.com/).
All RegExs must start and end with a forward slash. The bits inbetween are as follows.
http: is simply selecting a string that starts with "http:"
\/\/ is called "escaping" and that will select two forward slashes. Since forward slashes are special characters used in RegEx (start and end of a statement) they need to be escaped so that PHP doesn't think the RegEx has ended sooner.
(.+) The brackets are also special characters (though not escaped) and they are known as "capture groups". What this is used for is so that I can see what is between the "http://" and the ".com" (or whatever extension is used). The full stop (or period or ".") character selects anything.
\. Further on the escaping. Since full stop is used as a special character, we have to escape this one. What that means so far is that we are selecting "http://" then anything and then stopping at a full stop.
(.+) Last but not least is the final capture group. This, again selects anything from the string so that have our final capture group and RegEx complete.
Modifiers:
? means "one or more of the preceding character". This means that /tests?/ would match test and tests since s is the preceding character and in the first example we have 0 and in the second there is 1
+ means "one of more of the preceding character". In this case we are saying one of more of anything which means we expect at least one character to be provided.
The second parameter is our replace part.
In short, the $1 and $2 sections are to reference the two brackets from the above RegEx.
Some further reading
The PHP function I used
More information on Regular Expressions
RegEx capture groups
$string = 'helloo im nice, have a look http://www.cute.com';
$string = str_replace('http://', '', $string);
echo $string;
I have the following Regex to allow alphanumeric characters and following special characters
/()-
The Regular expression is
/[^A-Za-z0-9-()-/]/
The complete method is
public function ValidateNumber($number)
{
$return = true;
$matches = null;
if((preg_match('/[^A-Za-z0-9-/()-]/', $number, $matches)) > 0)
{
$return = false;
}
return $return;
}
Above method woks fine, but also return TRUE if number has space. When i remove '/' from Regex then if number has 'space' in it then it returns FALSE.
So seems some issue with '/' in Regex.
Please advise some solution
Use this:
$theregex = '~^[a-z0-9/()-]+$~i';
if (preg_match($theregex, $yourstring)) {
// Yes! It matches!
}
else { // nah, no luck...
}
Explanation
The i flag at the end makes it case-insensitive
The ^ anchor asserts that we are at the beginning of the string
To match a hyphen in a [character class], place it at the beginning or at the end so that it is not ambiguous, since it may indicate a range, as in a-d
[a-z0-9/()-]+ matches one or more letter, digit, slash, parenthesis or hyphen
The $ anchor asserts that we are at the end of the string
Regex to allow alphanumeric characters and the the above mentioned special characters /()-,
^[A-Za-z0-9()\/-]+$
^ inside(at the strat of) chracter class means not. So your regex allows any character not of the ones mentioned inside the character class. And also it's better to escape / inside the character class and always consider in putting - at the start or end of the character class. To allow one ore more characters which was mentioned inside char class then you need to add + after the character class.
Explanation:
^ the beginning of the string
[A-Za-z0-9()\/-]+ any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9', '(', ')', '\/', '-' (1 or more
times)
$ before an optional \n, and the end of the
string
You should escape / in your regex using \/
But you should probably use the following expression to do what you want:
([^A-Za-z0-9-()-\/])+
So the whole method could look like this:
public function ValidateNumber($number)
{
if (preg_match('/([^A-Za-z0-9-()-\/])+/', $number)) {
return false;
}
return true;
}
without extra variables.
In above case you try to find any characters that don't match (here ^ means characters that don't match) your criteria and if any of them is found preg_match return 1 so it means that number is invalid.
However you can also use another expression to achieve what you want - you don't find characters that don't match (as in previous example) but you check if the whole string matches your criteria using ^ as the beginning (in this case it means the beginning of the string - meaning is different that the one in previous solution) and $ as the end of the string to check the whole string. In this case your method could look like this:
public function ValidateNumber($number)
{
if (preg_match('/^([A-Za-z0-9-()-\/]+)$/', $number)) {
return true;
}
return false;
}
For Much better understanding and learning regex for the further work you can visit the below links
Learning Regular Expressions
Useful regular expression tutorial
Regular expressions tutorials
And one of the best and easy one and my favourite is
http://www.9lessons.info/2013/10/understanding-regular-expression.html?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+9lesson+%289lessons%29
very nice and easy tutorial for the beginners
I am porting code from Node.js to PHP and keep getting errors with this regular expression:
^/[a-z0-9]{6}([^0-9a-z]|$)
PHP complains about a dollar sign:
Unknown modifier '$'
In JavaScript I was able to check if a string was ending with [^0-9a-z] or END OF STRING.
How do I do this in PHP with preg_match()?
My PHP code looks like this:
<?
$sExpression = '^/[a-z0-9]{6}([^0-9a-z]|$)';
if (preg_match('|' . $sExpression . '|', $sUrl)) {
// ...
}
?>
The JavaScript code was similar to this:
var sExpression = '^/[a-z0-9]{6}([^0-9a-z]|$)';
var oRegex = new RegExp(sExpression);
if (oRegex.test(sUrl)) {
// ...
}
To match a string that starts with a slash, followed by six alphanumerics and is then followed by either the end-of-string or something that's not alphanumeric:
preg_match('~^/[a-z0-9]{6}([^0-9a-z]|$)~i', $str);
The original JavaScript probably used new RegExp(<expression>), but PCRE requires a proper enclosure of the expression; those are the ~ characters I've put in the above code. Btw, I've made the expression case insensitive by using the i modifier; feel free to remove it if not desired.
You were using | as the enclosure; as such, you should have escaped the pipe character inside the expression, but by doing so you would have changed the meaning. It's generally best to choose delimiters that do not have a special meaning in an expression; it also helps to choose delimiters that don't occur as such in the expression, e.g., my choice of ~ avoids having to escape any character.
Expressions in PCRE can be generalised as:
<start-delimiter> stuff <end-delimiter> modifiers
Typically, the starting delimiter is the same as the ending delimiter, except for cases such as [expression]i or {expression}i whereby the opening brace is matched with the closing brace :)
Fix the regular expression first:
^/[a-z0-9]{6}([^0-9a-z]|$)
Try this.
As others pointed out, I'm an idiot and saw a / as a \ ... LOL.
Ok, well go at this again,
I’d avoid using the "|" and just do it this way.
if (preg_match('/^\/[a-z0-9]{6}([^0-9a-z]|$)/', $sUrl)) { ... }
Reducing this to just matching a particular character or end of string (PHP),
\D777(\D|$)\
This will match:
xxx777xxx or xxx777 but not xxx7777 or xxx7777xxx
Given the following string how can I match the entire number at the end of it?
$string = "Conacu P PPL Europe/Bucharest 680979";
I have to tell that the lenght of the string is not constant.
My language of choice is PHP.
Thanks.
You could use a regex with preg_match, like this :
$string = "Conacu P PPL Europe/Bucharest 680979";
$matches = array();
if (preg_match('#(\d+)$#', $string, $matches)) {
var_dump($matches[1]);
}
And you'll get :
string '680979' (length=6)
And here is some information:
The # at the beginning and the end of the regex are the delimiters -- they don't mean anything : they just indicate the beginning and end of the regex ; and you could use whatever character you want (people often use / )
The '$' at the end of the pattern means "end of the string"
the () means you want to capture what is between them
with preg_match, the array given as third parameter will contain those captured data
the first item in that array will be the whole matched string
and the next ones will contain each data matched in a set of ()
the \d means "a number"
and the + means one or more time
So :
match one or more number
at the end of the string
For more information, you can take a look at PCRE Patterns and Pattern Syntax.
The following regex should do the trick:
/(\d+)$/
EDIT: This answer checks if the very last character in a string is a digit or not. As the question https://stackoverflow.com/q/12258656/1331430 was closed as an exact duplicate of this one, I'll post my answer for it here. For what this question's OP is requesting though, use the accepted answer.
Here's my non-regex solution for checking if the last character in a string is a digit:
if (ctype_digit(substr($string, -1))) {
//last character in string is a digit.
}
DEMO
substr passing start=-1 will return the last character of the string, which then is checked against ctype_digit which will return true if the character is a digit, or false otherwise.
References:
substr
ctype_digit
To get the number at the end of a string, without using regex:
function getNumberAtEndOfString(string $string) : ?int
{
$result = sscanf(strrev($string), "%d%s");
if(isset($result[0])) return strrev($result[0]);
return null;
}
var_dump(getNumberAtEndOfString("Conacu P PPL Europe/Bucharest 680979")); //int(680979)