如何替换除文本以外的所有内容[重复]
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>
此问题已经存在 这里有一个答案: p>
-
如何替换字符串的某些部分?
5个答案\ r
span>
li>
ul>
div>
我正在寻找替换除了两个文本之外的所有东西 php中的字符串 example:观看Sidney的视频 p>
我想用什么都不取代“观看视频”,只需保留“Sidney” p>
需要 以这种格式preg_replace(“正则表达式代码”,“替换为”,输入文本) p> 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];