Extract time within parentheses using PHP - php

This is my first time using the trim function and I want to get the Time excluding the open and close parenthesis of my string. Can you give me hints and suggestions on how to do this?
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
echo trim($string, "Updated by Carewina Almonte (04/02/2018");
exit();

In php, You can do get this and this works if and only if date and time always appears at the end of string -
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
$time = substr($string,-9,8);
echo $time;

$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
if(preg_match("/\d{2}:\d{2}:\d{2}/", $string , $match))
{
echo $match[0];
}
Regular expression should be used in this case.

You can use preg_match for this task:
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match('/(?<=\(\d{2}\/\d{2}\/\d{4} ).*(?=\))/', $str, $match);
echo $match[0];
Breakdown:
Positive Lookbehind (?<=\(). Assert that the Regex below matches:
\( matches the character ( literally (case sensitive)
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d{2} matches a digit (equal to [0-9])
{2} Quantifier — Matches exactly 2 times
\/ matches the character / literally (case sensitive)
Positive Lookahead (?=\)). Assert that the Regex below matches:
\) matches the character ) literally (case sensitive)

For you example string you might match what is between parenthesis using \(\K[^)]+(?=\)).
This will match an opening parenthesis \( and then use \K to reset the starting point of the reported match.
After that match NOT a closing parenthesis one or more times [^)]+ and a positive lookahead to assert that what follows is a closing parenthesis (?=\)).
Then you could create a DateTime using or use DateTime::createFromFormat using $matches[0] and extract the time:
$re = '/\(\K[^)]+(?=\))/';
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match($re, $str, $matches);
$dateTime = new DateTime($matches[0]);
if ($dateTime !== false) {
echo $dateTime->format('H:i:s');
}
Test

Related

split string in numbers and text but accept text with a single digit inside

Let's say I want to split this string in two variables:
$string = "levis 501";
I will use
preg_match('/\d+/', $string, $num);
preg_match('/\D+/', $string, $text);
but then let's say I want to split this one in two
$string = "levis 5° 501";
as $text = "levis 5°"; and $num = "501";
So my guess is I should add a rule to the preg_match('/\d+/', $string, $num); that looks for numbers only at the END of the string and I want it to be between 2 and 3 digits.
But also the $text match now has one number inside...
How would you do it?
To slit a string in two parts, use any of the following:
preg_match('~^(.*?)\s*(\d+)\D*$~s', $s, $matches);
This regex matches:
^ - the start of the string
(.*?) - Group 1 capturing any one or more characters, as few as possible (as *? is a "lazy" quantifier) up to...
\s* - zero or more whitespace symbols
(\d+) - Group 2 capturing 1 or more digits
\D* - zero or more characters other than digit (it is the opposite shorthand character class to \d)
$ - end of string.
The ~s modifier is a DOTALL one forcing the . to match any character, even a newline, that it does not match without this modifier.
Or
preg_split('~\s*(?=\s*\d+\D*$)~', $s);
This \s*(?=\s*\d+\D*$) pattern:
\s* - zero or more whitespaces, but only if followed by...
(?=\s*\d+\D*$) - zero or more whitespaces followed with 1+ digits followed with 0+ characters other than digits followed with end of string.
The (?=...) construct is a positive lookahead that does not consume characters and just checks if the pattern inside matches and if yes, returns "true", and if not, no match occurs.
See IDEONE demo:
$s = "levis 5° 501";
preg_match('~^(.*?)\s*(\d+)\D*$~s', $s, $matches);
print_r($matches[1] . ": ". $matches[2]. PHP_EOL);
print_r(preg_split('~\s*(?=\s*\d+\D*$)~', $s, 2));

how can I replace [link](#) to link?

I want to do something like stackoverflow. actually changing this style []() to this style . here is my try:
$str = '[link](#)';
$str = str_replace('[','<a href="',$str); // output: <a href="link](#)
$str = str_replace(']','">',$str); // output: <a href="link">(#)
$str = str_replace('(','',$str); // output: <a href="link">#)
$str = str_replace(')','</a>',$str); // output: #
but now, I need to change link with #, how can I do that ?
You want to take a look at preg_replace(), with this you can use a regex to replace it, e.g.
$str = preg_replace("/\[(.*?)\]\((.*?)\)/", "<a href='$2'>$1</a>", $str);
regex explanation:
\[(.*?)\]\((.*?)\)
\[ matches the character [ literally
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\] matches the character ] literally
\( matches the character ( literally
2nd Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
\) matches the character ) literally

how to validate the first four character in string using php?

I want to make script that only accept the ff;
1st, 2nd, and 3rd character from a word/string/paragraph == ABC;
4th
character from a word/string/paragraph == asterisk(*);
5th to 20th from accept only a numeric integer...
<?php
$subject = "das*3445465656343";
$pattern = '/^[ABCabc]{3}$/';
preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
?>
This should work for you:
Just use this regex:
$pattern = "/^abc\*\d{16}$/i";
Explanation:
^ assert position at start of a line
abc matches the characters abc literally (case insensitive)
\* matches the character * literally
\d{16} match a digit [0-9]
Quantifier: {16} Exactly 16 times
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Demo
Check this regex: (?=^abc\*\d{16}$).+
DEMO

Get multiple matches in string between two strings - small issue in function that I use?

I have this input:
somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters
And I need to get this output:
array("object1", "object2", "object3");
I use this function:
function get_string_between($string, $start, $end){
$split_string = explode($end,$string);
foreach($split_string as $data) {
$str_pos = strpos($data,$start);
$last_pos = strlen($data);
$capture_len = $last_pos - $str_pos;
$return[] = substr($data,$str_pos+1,$capture_len);
}
return $return;
}
So:
$input = "somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters";
$start = "[code]";
$end = "[/code]";
$outputs = get_string_between($input, $start, $end);
foreach($outputs as $output)
echo "$output </br>";
But foreach return this:
code]object1
code]object2
code]object3
omerandomcharacters
Can you please help me where is the problem in the function? It looks like that work opposite than I need, isn't it?
Thank you.
$string = "somerandomcharacters[code]object1[/code]somerandomcharacters[code]object2[/code]somerandomcharacters[code]object3[/code]somerandomcharacters";
preg_match_all('%\[code\](.*?)\[/code\]%i', $string, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);
Output:
Array
(
[0] => object1
[1] => object2
[2] => object3
)
Regex Explanation:
\[code\](.*?)\[/code\]
Options: Case insensitive
Match the character “[” literally «\[»
Match the character string “code” literally (case insensitive) «code»
Match the character “]” literally «\]»
Match the regex below and capture its match into backreference number 1 «(.*?)»
Match any single character that is NOT a line break character (line feed) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “[” literally «\[»
Match the character string “/code” literally (case insensitive) «/code»
Match the character “]” literally «\]»
DEMO: http://ideone.com/wVvssx

Regex PHP - dont match specific string followed by numeric

Im looping over a large number of files in a directory, and want to extract all the numeric values in a filename where it starts lin64exe , for instance, lin64exe005458002.17 would match 005458002.17. I have this part sorted, but in the directory there are other files, such as part005458 and others. How can I make it so I only get the numeric (and . ) after lin64exe ?
This is what I have so far:
[^lin64exe][^OTHERTHINGSHERE$][0-9]+
Regex to match the number with decimal point which was just after to lin64exe is,
^lin64exe\K\d+\.\d+$
DEMO
<?php
$mystring = "lin64exe005458002.17";
$regex = '~^lin64exe\K\d+\.\d+$~';
if (preg_match($regex, $mystring, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
?> //=> 005458002.17
You can try with look around as well
(?<=^lin64exe)\d+(\.\d+)?$
Here is demo
Pattern explanation:
(?<= look behind to see if there is:
^ the beginning of the string
lin64exe 'lin64exe'
) end of look-behind
\d+ digits (0-9) (1 or more times (most possible))
( group and capture to \1 (optional):
\. '.'
\d+ digits (0-9) (1 or more times (most possible))
)? end of \1
$ the end of the string
Note: use i for ignore case
sample code:
$re = "/(?<=^lin64exe)\\d+(\\.\\d+)?$/i";
$str = "lin64exe005458002.17\nlin64exe005458002\npart005458";
preg_match_all($re, $str, $matches);
You can use this regex and use captured group #1 for your number:
^lin64exe\D*([\d.]+)$
RegEx Demo
Code:
$re = '/^lin64exe\D*([\d.]+)$/i';
$str = "lin64exe005458002.17\npart005458";
if ( preg_match($re, $str, $m) )
var_dump ($m[1]);

Categories