There have been several questions on this but none of them have lead me to the answer, they're all too specific or too long and complex. Mine is more general and simple. I have a pattern like this:
/you(?:.*)? see/
I want it to match all these sentences except the last:
you can see
you could see
you see
you could not see
At the moment it matches everything but it also matches the last sentence. I need it to only match any one single word or no word. I also tried this pattern but it doesn't quite work either:
/you(?:[^\s]+)? see/
This one does the job:
/^you(?:\s+\w+)?\s+see$/
Where (?:\s+\w+)? is an optional non capture group that matches 1 or more spaces followed by 1 or more word character (ie. [a-zA-Z-9_])
In action:
$strings = array(
'you can see',
'you could see',
'you see',
'you could not see',
);
foreach ($strings as $str) {
if (preg_match('/^you(?:\s+\w+)?\s+see$/', $str)) {
echo "$str : matches\n";
} else {
echo "$str : doesn't match\n";
}
}
Output:
you can see : matches
you could see : matches
you see : matches
you could not see : doesn't match
I would have deleted the question since I solved it shortly afterwards but there was already a response. I found just changing the pattern to this solved the problem:
/you(?:\s[^\s]+)? see/
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);
I need to check, if users input URL contains facebook(.any domain). This is what I have:
preg_match("/.(facebook)+\.[A-Z]{2,4}/", $input);
But on typying www.facebook.com it returns false. Could someone help me with this? I am not very good in regex.
That is because you are only matching for uppercase letters in the last part. You may want to make it match case independent by adding a modifier:
preg_match("/.(facebook)+\.[A-Z]{2,4}/i", $input);
The next things are:
you don't need to put "facebook" into a group
You don't need to quantify facebook
if you want to match a dot, then escape it
So end up with this:
preg_match("/\.facebook\.[A-Z]{2,4}/i", $input);
you can also try this along with the answer of #stema
if(strpos($url, "facebook") !== FALSE)
{
echo "exists";
}
else
{
echo "not exists";
}
I have a regex that validate a specific url but it not really working. I want to validate urls like this -----> https : // example.co.nz/#![RANDOM_KEYS_HERE].
I want to do it only with https. Most importantly, the input of the user need to match https : // example.co.nz/#! but after the #!, the user can put anything he like.
Here is the code:
I know that the code is fked up xD I have a basic knowledge in that lol
#^https://example+\.[co\.nz][a-z0-9-_.]+\.[a-z]{2,4}#i
If anyone could help me to do it, it would be great! thanks!
Erm... not even close. Your regex reads as follows:
Starting from the beginning of the string...
Match literally https://exampl
Match one or more e
Match a literal .
Match one of any of these: cnoz.
Match one or more of these: a-z0-9-_.
Match a literal .
Match between 2 and 4 letters
This is nothing like what you're looking for. After all, I don't think you want this to pass:
https://exampleeeeeeeeeeee.complete.and.total.failure.-_-.lol
Instead, try this:
(^https://example\.co\.nz/#!(.*))
This regex reads as follows:
Starting from the beginning of the string...
Match literally https://example.co.nz/#!
Capture everything thereafter
Try this out:
^https:\/\/example\.co\.nz\/\#\!(.*)$
The parentheses at the end will do a sub-expression match which should allow you to pull out the ID.
if (preg_match('/^https:\/\/example\.co\.nz\/\#\!(.*)$/', $searchString, $matches)) {
$id = $matches[1];
}
if (preg_match('%^https://example\.co\.nz/#!(.+)$%i', $subject)) {
# Successful match
} else {
# Match attempt failed
}
Or you can get your [RANDOM_KEYS_HERE] part with this one
if (preg_match('%^https://example\.co\.nz/#!(.+)$%i', $subject, $regs)) {
$result = $regs[0];
} else {
$result = "";
}
You don't need regexp there. You just need to find out if string starts with some substring. Check this:
if(strpos($url, 'https://example.co.nz/#!')===0)
{
echo 'url is OK';
}
else
{
echo 'url is wrong';
}
http://www.php.net/manual/en/function.strpos.php
I hope this helps.
I want to see if a variable contains a value that matches one of a few values in a hard-coded list. I was using the following, but recently found that it has a flaw somewhere:
if (preg_match("/^(init)|(published)$/",$status)) {
echo 'found';
} else {
echo 'nope';
}
I find that if the variable $status contains the word "unpublished" there is still a match even though 'unpublished' is not in the list, supposedly because the word 'unpublished' contains the word 'published', but I thought the ^ and $ in the regular expression are supposed to force a match of the whole word. Any ideas what I'm doing wrong?
Modify your pattern:
$pattern = "/^(init|published)$/";
$contain = "unpublished";
echo preg_match($pattern, $contain) ? 'found' : 'nope' ;
This pattern says our string must be /^init$/ or /^published$/, meaning those particular strings from start to finish. So substrings cannot be matched under these constraints.
In this case, regex are not the right tool to use.
Just put the words you want your candidate to be checked against in an array:
$list = array('init', 'published');
and then check:
if (in_array($status, $list)) { ... }
^ matches the beginning of a string. $ matches the end of a string.
However, regexes are not a magic bullet that need to get used at every opportunity.
In this case, the code you want is
if ( $status == 'init' || $status == 'published' )
If you are checking against a list of values, create an array based on those values and then check to see if the key exists in the array.
I am searching through text line by line and want to see if the line contains the phrase "see details" and is not case sensitive, so will find:
See Details, See details, SEE Details etc
I have this so far.
if(preg_match("/^(\see details)/", strtolower($line)))
{
echo 'SEE DETAILS FOUND';
}
A simple example would be helpful thanks.
If you want to check if a sub-string is present in a string, no need for regular expressions : stripos() will do just fine :
if (stripos(strtolower($line), 'see details') !== false) {
// 'see details' is in the $line
}
stripos() will return the position of the first occurrence of the sub-string in the string ; or false if the sub-string is not found.
Which means that if it returns something else than false, the sub-string is found.
Your regex is actually broken.
/^(\see details)/
This breaks down into:
At the beginning
Open a capturing group
Look for one whitespace character
Followed by all of the following characters: ee details
Close the group
\s is an escape sequence matching whitespace. You could also have added the i modifier to make the regex case-insensitive. You also don't seem to be doing anything with the captured group, so you can ditch that.
Therefore:
/^see details/i
is what you'd want.
You mentioned that you're going through input line by line. If you only need to know that the entire input contains the specific string, and you have the input as a string, you can use the m modifier to make ^ match "beginning of a line" instead of / in addition to "beginning of the string":
/^see details/im
If this is the case, then you would end up with:
if(preg_match('/^see details/im', $whole_input)) {
echo "See Details Found!";
}
But as others have mentioned, a regex isn't needed here. You can (and should) do the job with the more simple stripos.
As Pascal said, you can use stripos() function although correct code would be:
if (stripos(strtolower($line), 'see details') !== false) {
// 'see details' is in the $line
}
accoding to the php documentation (http://www.php.net/manual/en/function.preg-match.php):
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
which it looks pretty simple and nice :-).