This question already has an answer here:
I'm looking to replace every thing except text between two string in php example: Watch Sidney's video
i want to replace "Watch 's video" with nothing and just keep "Sidney"
need to be in this format preg_replace("regex code", "replace with", input text)
</div>
You can do it using the following regex :
/Watch (\w*)'s video/
and you can replace with \1
Live demo here
Update
Sample code in php :
echo preg_replace('/Watch (\w*)\'s video/', "\\1", 'Watch Sidney\'s video');
Output
Sidney
You can make use of following explode()
function for this:
$returnValue = explode(' ', 'Watch Sidney\'s video');
This will return an array as:
array (
0 => 'Watch',
1 => 'Sidney's',
2 => 'video',
)
Now check the entries of array for string with 's and once you get it, trim 's off as :
$myString str_replace("\'s","",$returnValue[some_index]);
This'll give you the text between the first space and the first apostrophe (assuming these criteria are constant):
<?php
$message = "Watch Sidney's video";
$start = strpos($message, " ");
$finish = strpos($message, "'");
echo substr($message, $start, $finish-$start);
// replace apostrophe (') or words without possessive contraction ('s) (Watch, video) with empty string
preg_replace("/(?:'|\s?\b\w+\b\s?)(?!'s)/", "", "Watch Sidney's video") // => Sidney
Try it here: https://regex101.com/r/sC7GyQ/1
If you want to extract video author's name - you may use extracting preg_match like this:
$matches = [];
preg_match('@Watch (\w+)\'s video@', $source, $matches);
echo $matches[1];