I have a string with movie titles and release year. I want to be able to detect the Title (Year) pattern and if matched wrap it in anchor tags.
Wrapping it is easy. But is it possilbe to write a regex to match this pattern if I don't know what the name of the movie would be?
Example:
$str = 'A random string with movie titles in it.
Movies like The Thing (1984) and other titles like Captain America Civil War (2016).
The movies could be anywhere in this string.
And some movies like 28 Days Later (2002) could start with a number.';
So the pattern will always be Title
(starting with uppercase letter) and will end with (Year)
.
This is what I have got so far:
if(preg_match('/^\p{Lu}[\w%+\/-]+\([0-9]+\)/', $str)){
error_log('MATCH');
}
else{
error_log('NO MATCH');
}
This currently does not work. From what I understand this is what it should do:
^\p{Lu} //match a word beginning with an uppercase letter
[\w%+\/-] //with any number of characters following it
+\([0-9]+\) //ending with an integer
Where am I going wrong with this?
The following regex should do it :
(?-i)(?<=[a-z]\s)[A-Z\d].*?\(\d+\)
Explanation
(?-i)
case-sensitive(?<=[a-z]\s)
look-behind for any lower-case letter and space [A-Z\d]
match an upper-case letter or digit.*?
match any character\(\d+\)
match any digits including parenthesisPHP
<?php
$regex = '/(?-i)(?<=[a-z]\s)[A-Z\d].*?\(\d+\)/';
$str = 'A random string with movie titles in it.
Movies like The Thing (1984) and other titles like Captain America Civil War (2016).
The movies could be anywhere in this string.
And some movies like 28 Days Later (2002) could start with a number.';
preg_match_all($regex, $str, $matches);
print_r($matches);
?>