I'm having troubles finding a regex that can retrieve the numbers 989552 in
/boards/989552-lettersandnumbers-morelettersandnumbers
What I'm searching in particular is can I retrieve what stands between /boards/ and the first -?
/boards/(\d+)-
Should store the numbers in the first match group.
Use .*/(\d+)- as .* is greedy it will match upto the last /:
$string = "/boards/989552-dgw25235-42352gdsgw";
echo preg_match('#.*/(\d+)-#',$string,$match);
echo $match[1];
>>> 989552
Here is an annotated solution.
<?php // RAY_temp_user1722791.php
error_reporting(E_ALL);
/*
I'm having troubles finding a regex that can retrieve the numbers 989552 in /boards/989552-lettersandnumbers-morelettersandnumbers
What I'm searching in particular is can I retrieve what stands between /boards/ and the first -?
*/
// A REGULAR EXPRESSION
$rgx
= '#' // REGEX DELIMITER
. '/boards/' // THE SEARCH STRING
. '(' // START A GROUP
. '\d+' // SOME DIGITS
. ')' // END OF THE GROUP
. '-' // THE DASH
. '#' // REGEX DELIMITER
;
// A TEST STRING
$str = 'in /boards/989552-lettersandnumbers';
// PEFORM THE MATCH
preg_match($rgx, $str, $mat);
// FIND THE NUMBERS IN THE FIRST MATCHED GROUP
var_dump($mat[1]);
I find it much easier to understand regular expressions when I write them out in vertical notation like this.
Related
The code below works perfectly:
$string = '(test1)';
$new = preg_replace('/^\(+.+\)+$/','word',$string);
echo $new;
Output:
word
If the code is this:
$string = '(test1) (test2) (test3)';
How to generate output:
word word word?
Why my regex do not work ?
^ and $ are anchors which means match should start from start of string and expand upto end of string
. means match anything except newline, + means one or more, by default regex is greedy in nature so it tries to match as much as possible where as we want to match ( ) so we need to change the pattern a bit
You can use
\([^)]+\)
$string = '(test1) (test2) (test3)';
$new = preg_replace('/\([^)]+\)/','word',$string);
echo $new;
Regex Demo
I am trying to capture date from a file file-2018-02-19-second.json.
I am using .*file-(..........).*.json regex to capture the date in the file .The regex is capturing 2018-02-19 date in the file but I want to ignore "-" in the file and only capture 20180219. How can I do it?
If your filenames have always the same format, you can convert your string to a DateTime instance using DateTime::createFromFormat:
$date = DateTime::createFromFormat('*-Y-m-d-*.*', 'file-2018-02-19-second.json');
echo $date->format('Ymd');
You can find the different format characters and their meanings in the php manual.
$fileName = 'file-2018-02-19-second.json';
preg_match('#([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))#is', $fileName,
$output);
if (!empty($output)) {
$date = preg_replace('#-#is', '', $output[1]);
echo $date;
}
hope can help you!
related link: https://www.regextester.com/96683
Option 1 - Match & Replace
See code in use here
<?php
$fn = 'file-2018-02-1-second.json';
$fn = preg_match('/.*file-\K\d{4}-\d{2}-\d{2}/', $fn, $o);
echo isset($o[0]) ? preg_replace('/\D+/', '', $o[0]) : 'No match found';
Option 2 - Group & Concatenate
See code in use here
<?php
$fn = 'file-2018-02-1-second.json';
$fn = preg_match('/.*file-(\d{4})-(\d{2})-(\d{2})/', $fn, $o);
echo isset($o[1], $o[2], $o[3]) ? $o[1].$o[2].$o[3] : 'No match found';
Explanation of Patterns
.*file-\K\d{4}-\d{2}-\d{2}
.* Match any character any number of times
file- Match this literally
\K Resets the starting point of the match. Any previously consumed characters are no longer included in the final match.
\d{4} Match any digit exactly 4 times
- Match this literally
\d{2} Match any digit exactly 2 times
- Match this literally
\d{2} Match any digit exactly 2 times
The second pattern \D+ simply matches any non-digit character one or more times for replacement.
The last pattern (from option 2) is really just the simplified version of the first pattern I described, but groups each number part into capture groups.
Result: 20180219
This question appears to be solely about data extract, not about data validation.
Code: (Demo)
$file = 'file-2018-02-19-second.json';
$date = preg_replace('~\D+~', '', $file);
echo $date;
Output:
20180219
If you need slightly more accuracy/validation than that (leveraging the location of file-, you can use \G to extract the date components before imploding them.
Code: (Demo) (Pattern Demo)
$file = 'somefile-2018-02-19-second.json';
echo preg_match_all('~\Gfile-\K\d+|-\K\d+~', $file, $out) ? implode($out[0]) : 'fail';
// same result as earlier method
I'm trying to check for
'#username'
'#username,'
'#username '
'#username.'
'#username. '
'#username:'
'#username: '
I currently have this:
$post->message = preg_replace(
'/# *('.preg_quote($speak['username'], '/').') *:/i',
'[url=\''.PAGE_URL.RELATIVE_WBB_DIR.'/index.php?page=User&userID='.$speak['toID'].'\']#'.$speak['username'].':[/url]',
$post->message);
Does anyone have any ideas how I can modify this to accept those inputs?
Modify your regex to add in the punctuation:
$post->message = preg_replace(
'/# *('.preg_quote($speak['username'], '/').')[:,.]? */i',
'[url=\''.PAGE_URL.RELATIVE_WBB_DIR.'/index.php?page=User&userID='.$speak['toID'].'\']#'.$speak['username'].':[/url]',
$post->message);
Note the added part:
/# *('.preg_quote($speak['username'], '/').')[:,.]? */i
^^^^^^
Which optionally matches one of those characters (colon, comma, period).
Here is a regular expression that should achieve what you are looking for:
/^#[a-zA-Z]+[:\.\,]?[ ]?$/
/^# // string starts with '#'
[a-zA-Z]+ // contains any letter at least once
[:\.\,]? // may contain any : , . zero or one time
[ ]?$ // may contain a whitespace zero or one time at end of string
I am trying to use preg_match to find a certain word in a string of text.
$pattern = "/" . $myword . "/i";
This pattern will find the word "car" inside "cartoon"...
I need just matches where the certain word appears.
P.S The word may be anywhere inside the text.
Thanks
Wrap your regex with word-boundaries:
$pattern = "/\b" . $myword . "\b/i";
or, if your $myword may contain regex-meta-chars, do:
$pattern = "/\b" . preg_quote($myword) . "\b/i";
Try this:
$pattern = "/\b" . $myword . "\b/i";
In regular expressions, the \b escape character represents a "word boundary" character. By wrapping your search term within these boundary matches, you ensure that you will only match the word itself.
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREenter code hereG_OFFSET_CAPTURE, 3);
print_r($matches);
pattern
The pattern to search for, as a string.
subject
The input string.
matches
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
flags
flags can be the following flag:
PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
offset
Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).
Example:
if (preg_match('/;/', $_POST['value_code']))
{
$input_error = 1;
display_error(_("The semicolon can not be used in the value code."));
set_focus('value_code');
}
I am trying to make sense of handling regular expression with php. So far my code is:
PHP code:
$string = "This is a 1 2 3 test.";
$pattern = '/^[a-zA-Z0-9\. ]$/';
$match = preg_match($pattern, $string);
echo "string: " . $string . " regex response: " , $match;
Why is $match always returning 0 when I think it should be returning a 1?
[a-zA-Z0-9\. ] means one character which is alphanumeric or "." or " ". You will want to repeat this pattern:
$pattern = '/^[a-zA-Z0-9. ]+$/';
^
"one or more"
Note: you don't need to escape . inside a character group.
Here's what you're pattern is saying:
'/: Start the expressions
^: Beginning of the string
[a-zA-Z0-9\. ]: Any one alphanumeric character, period or space (you should actually be using \s for spaces if your intention is to match any whitespace character).
$: End of the string
/': End the expression
So, an example of a string that would yield a match result is:
$string = 'a'
Of other note, if you're actually trying to get the matches from the result, you'll want to use the third parameter of preg_match:
$numResults = preg_match($pattern, $string, $matches);
You need a quantifier on the end of your character class, such as +, which means match 1 or more times.
Ideone.