Reputation: 4693
I have special words in a string that i would like to capture based on the prefix.
Example Special words such as ^to_this should be caught
.
I would need the word this
because of the special prefix ^to_
.
Here is my attempt but it is not working
preg_match('/\b(\w*^to_\w*)\b/', $str, $specialWordArr);
but this returns an empty array
Upvotes: 0
Views: 140
Reputation: 174874
Your code would be,
<?php
$mystring = 'Special words such as ^to_this should be caught';
$regex = '~[_^;]\w+[_^;](\w+)~';
if (preg_match($regex, $mystring, $m)) {
$yourmatch = $m[1];
echo $yourmatch;
}
?> //=> this
Explanation:
[_^;]
Add the special characters into this character class to ensure that the begining of a word would be a special character.\w+
After a special character, there must one or more word characters followed.[_^;]
Word characters must be followed by a special character.(\w+)
If these conditions are satisfied, capture the following one or more word characters into a group. Upvotes: 2
Reputation: 4784
Without some additional examples this will work for what you've posted:
$str = 'Special words such as ^to_this should be caught';
preg_match('/\s\^to_(\w+)\s/', $str, $specialWordArr);
echo $specialWordArr[1]; //this
Upvotes: 1