I don't know almost anything about regex, but I need to allow only one space between letters, this is what I have done with another questiona and answer, plus random tries with regex101:
/^(\d){1,}(\:[A-Za-z0-9-]+([ a-zA-Z0-9-]+)?)?\:(\d){1,}(?:\.(\d){1,2})?$/m
The fomat should be:
[integer]:[optional label :][integer/decimal]
Example:
12:aaa:12.31
56:a s f:15
34:45.8
I have done some random tries without any success,I'm only able to allow infinite space, could someone help me? I have also looked at others answers, but I couldn't implement in my regex.
Check if error:
preg_match_all('/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/mi', $_POST['ratetable'], $out);
if($out[0]!=explode("\n",$_POST['ratetable'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array(0=>'Invalid price table at line: '.implode(", ", array_diff_key(array_flip(explode("\n",$_POST['ratetable'])),array_flip($out[0])))));
exit();
}
You could make the regex a bit shorter and allow a single space in between each letter like this:
/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/gmi
regex101 demo
If you want to capture only the label (and exclude the :) in the capture, you can use this one.
I think
^\d+:([^:]+:)?\d+(\.\d+)?$
might do it...
It means: <int> + ":" + [label + ":"] + <float> where label can be anything but :.
You're nearly there:
(?: [a-zA-Z0-9-]+)*
the above would mean: space followed by at least one in the character group; the latter group any number of times, without capturing
You can use preg_match
$str = 'Another Example String 1_2-3';
echo $str . "<br />\n";
if (preg_match('#^(?:[\w-]+ ?)+$#', $str)){
echo 'Legal format!';
} else {
echo 'Illegal format!';
}
^\d+:([\w\d]+ ?)*:?\d+(\.\d+)?$
Live demo
Related
I have the following title formation on my website:
It's no use going back to yesterday, because at that time I was... Lewis Carroll
Always is: The phrase… (author).
I want to delete everything after the ellipsis (…), leaving only the sentence as the title. I thought of creating a function in php that would take the parts of the titles, throw them in an array and then I would work each part, identifying the only pattern I have in the title, which is the ellipsis… and then delete everything. But when I do that, in the X space of my array, it returns the following:
was...
In position 8 of the array comes the word and the ellipsis and I don't know how to find a pattern to delete the author of the title, my pattern was the ellipsis. Any idea?
<?php
$a = get_the_title(155571);
$search = '... ';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
?>
I tried with the code above and found the ellipsis, but I needed to bring it into an array to delete the part I need. I tried something like this:
<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
global $wpdb;
$title_array = explode(' ', get_the_title(155571));
$search = '... ';
if (array_key_exists("/{$search}/i",$title_array)) {
echo "true";
}
?>
I started doing it this way, but it doesn't work, any ideas?
Thanks,
If you use regex you need to escape the string as preg_quote() would do, because a dot belongs to the pattern.
But in your simple case, I would not use a regex and just search for the three dots from the end of the string.
Note: When the elipsis come from the browser, there's no way to detect in PHP.
$title = 'The phrase... (author).';
echo getPlainTitle($title);
function getPlainTitle(string $title) {
$rpos = strrpos($title, '...');
return ($rpos === false) ? $title : substr($title, 0, $rpos);
}
will output
The phrase
First of all, since you're working with regular expressions, you need to remember that . has a special meaning there: it means "any character". So /... / just means "any three characters followed by a space", which isn't what you want. To match a literal . you need to escape it as \.
Secondly, rather than searching or splitting, you could achieve what you want by replacing part of the string. For instance, you could find everything after the ellipsis, and replace it with an empty string. To do that you want a pattern of "dot dot dot followed by anything", where "anything" is spelled .*, so \.\.\..*
$title = preg_replace('/\.\.\..*/', '', $title);
For my PHP script I have this code:
if (!preg_match("/[^A-Za-z]/", $usersurname))
$usersurname_valid = 1;
This worked untill I realized a surname can be two or more words... doh.
Anyone can tell me how to write this code if I want to allow 1 space between two worlds? For example:
Jan Klaas is now wrong and Jan Klaas should be allowed, also Jan Klaas Martijn and so on should be allowed.
Even better would be a preg replace, to replace two or more spaces with 1, so when you write: Jan(space)(space)Klaas or Jan(space)(space)(space)(space)Klaas, it would return Jan(space)Klaas.
I searched around for a while but somehow I just can't get this space matching to work..
PS: When I got this working, I will apply this for the mid and last name too ofcourse.
===========================================
EDIT: After you helping me out, I re-wrote my code to:
// validate usersurname
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usersurname))
$usersurname_valid = 1;
// validate usermidname
$usermidname = preg_replace("/\s{2,}/"," ", $usermidname);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usermidname))
$usermidname_valid = 1;
// validate userforename
$userforename = preg_replace("/\s{2,}/"," ", $userforename);
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$userforename))
$userforename_valid = 1;
and the error notifications
elseif ($usersurname_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the last name. $usersurname $usermidname $userforename</p>");
// usermidname character validation
elseif ($usermidname_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the middle name. $usersurname $usermidname $userforename</p>");
// userforename character validation
elseif ($userforename_valid !=1)
echo ("<p id='notification'>Only alphabetic character are allowed for the (EDIT) first name. $usersurname $usermidname $userforename</p>");
Replacing the spaces are working well and I need this preg_match to check on on A-Za-z + space. I think in this case it doesn't matter if it's matching more than 1 spaces because it's replaced anyway, right?
EDIT:
Solution for my case:
$usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
if (!preg_match("/[^A-Za-z ]/", $usersurname))
This does the work. Thanks for helping out, J0HN
Well, solving the problem you have in mind:
if (!preg_match("/^[A-Za-z]+(\s[A-Za-z]+)*$/",$usersurname)) { ... }
But, well, it's just a part of the solution, and it's not bulletproof. Look at the list of common mistakes when handling names.
So, you'd better to re-think on your validation approach.
Replacing the multiple spaces is simpler to achieve as a separate instruction, something like
$processed_usersurname = preg_replace("/\s{2,}/"," ", $usersurname);
This will match and replace any two or more consequent whitespace characters (space, tab, linebreak and carriage return) to single space
I'm using this code to validate string.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
How if I want to validate if the number contain "+" sign in front or not?
Such as :
$countrecipient ='+0123456789';
and still need to validate the rest of the string.
I tried this:
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
{
echo "Ok";
}
else
{
echo "Error";
}
It works in my pc but I'm not sure why my customer is complaining it shows him error.
Thank you.
For an optional plus in front you could use:
preg_match('/^\+?[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient);
Notice how I have escaped the + with a backslash? This is because it is a regex keyword which means 1 instance or more.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
You're making things unnecessarily complicated. "[0]{1}[1]{1}[0-9]{1}" reduces to simply "01[0-9]".
To have an optional + on the front, your basic idea of using [+] should work. Let's see...
$countrecipient ='+0123456789';
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
...again this can be simplified, but it simplies to /^[+]601[0-9][0-9]{7}?$/. Where did the 6 after the + come from? Does this account for your problem?
Plus has a special meaning in PCRE, it's called quantifier and has meaning of {1,}.
You may either put in into character group specification like this [+] which would literally mean one of following characters: array( '+') or escape it with \ so you'll get: \+.
Also adding {1} is implicit and you don't have to add it after one character. If you were doing this matching foo would look like: f{1}o{1}o{1}, ehm f{1}o{2} instead of foo :)
If you want to match both 0123456789 and +012345678 you should use {0,1} which has "shortcut" ?. Than your pattern would look like: /\+?/. I guess your desired regexp is:
/^\+?0?1?[0-9]([0-9]{7})?$/
The simplified form of your regex is
/\+?01[0-9]{8}/
However I recommend you use intval, is_int, ctype_digit to accomplish this.
if(intval($str)<=100000000){
// found it.
}
Based on regexp you put in the section you tried: "...preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/'..."
If you would validate the string AND check if there is a '+' or not, you could use something like this:
if(preg_match('/(\+)?6011[0-9][0-9]{7}?$/', $countrecipient, $matches))
{
if ($matches[1] == '+') {
echo "Ok WITH PLUS";
} else {
echo "Ok without PLUS";
}
}
else
{
echo "Error";
}
I want a regex solution to allow only
http://www.imdb.com/title/ttANYNumberWOrdetc/ links
Otherwise SHOW us error.. Incorrect link
I am not too good with regex
I just create this petren ..
preg_match('/http:\/\/www.imdb.com\/title\/(.*)\//is', 'http://www.imdb.com/title/tt0087469/', $result);
Its show me corect result but i think i missed some thing..
Thanks,
How about something like this: http://(?:www\.)?imdb.com/title/tt[^/]+/.
Example:
<?php
if ( preg_match('#^http://(?:www\.)?imdb\.com/title/tt[^/]+/$#', 'http://www.imdb.com/title/tt0448303/') )
echo 'Matches' . PHP_EOL;
Explanation:
The regular expression matches a string that starts with http:// followed either by imdb.com or www.imdb.com, then /title/tt followed by any character except for a / and that ends with a /.
The # is the delimiter, the ^ indicated the beginning of the string and the $ the end.
This should work:
if (preg_match("#^(http://www.|https://www.)imdb.com/title/tt([a-zA-Z0-9]+)(?:/)(?:^[a-zA-Z0-9]+)?$#s", 'http://www.imdb.com/title/tt0364845/', $matches)) {
echo 'yay';
} else {
echo 'nay';
}
I would like to know how I could find out in PHP if a variable only contains 1 word. It should be able to recognise: "foo" "1326" ";394aa", etc.
It would be something like this:
$txt = "oneword";
if($txt == 1 word){ do.this; }else{ do.that; }
Thanks.
I'm assuming a word is defined as any string delimited by one space symbol
$txt = "multiple words";
if(strpos(trim($txt), ' ') !== false)
{
// multiple words
}
else
{
// one word
}
What defines one word? Are spaces allowed (perhaps for names)? Are hyphens allowed? Punctuation? Your question is not very clearly defined.
Going under the assumption that you just want to determine whether or not your value contains spaces, try using regular expressions:
http://php.net/manual/en/function.preg-match.php
<?php
$txt = "oneword";
if (preg_match("/ /", $txt)) {
echo "Multiple words.";
} else {
echo "One word.";
}
?>
Edit
The benefit to using regular expressions is that if you can become proficient in using them, they will solve a lot of your problems and make changing requirements in the future a lot easier. I would strongly recommend using regular expressions over a simple check for the position of a space, both for the complexity of the problem today (as again, perhaps spaces aren't the only way to delimit words in your requirements), as well as for the flexibility of changing requirements in the future.
Utilize the strpos function included within PHP.
Returns the position as an integer. If needle is not found, strpos()
will return boolean FALSE.
Besides strpos, an alternative would be explode and count:
$txt = trim("oneword secondword");
$words = explode( " ", $txt); // $words[0] = "oneword", $words[1] = "secondword"
if (count($words) == 1)
do this for one word
else
do that for more than one word assuming at least one word is inputted