0

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)

0m3r
  • 12,286
  • 15
  • 35
  • 71

5 Answers5

1

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
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
  • sorry not working it will be in wordpress plugin option so cant put all this code right now im using preg_replace("/\'s(.*)/", "", input text) this code replace every thing except "Watch " and Sidney just need to replace "Watch " to – Roger Kaputnik Oct 30 '17 at 05:42
  • 1) you dont have to use all this code, you can simply substitute the value of all the variables in `preg_replace`. 2) you dont have "watch to" in your question, can you give a clear sample input and ouput? @RogerKaputnik – Ashish Ranjan Oct 30 '17 at 05:45
  • @RogerKaputnik also here's a working sample : https://ideone.com/4MYS8m , is this what's required? – Ashish Ranjan Oct 30 '17 at 05:53
  • preg_replace("/\'s(.*)/", "", Watch Sidney's video) > Watch Sidney just need replace the word Watch – Roger Kaputnik Oct 30 '17 at 05:53
  • you can mark the answer as correct if it does answer the question correctly, helps future visitors find answers to their question. @RogerKaputnik – Ashish Ranjan Oct 30 '17 at 06:14
0

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]);
Abhishek
  • 539
  • 5
  • 25
0

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);
Gary Browne
  • 87
  • 3
  • 11
0
// 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

omijn
  • 646
  • 1
  • 4
  • 11
0

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];
Oleg Loginov
  • 337
  • 1
  • 6