使用PHP替换字符串中的文本 [英] Replace text in a string using PHP
问题描述
我有这个字符串:
$my_string = "http://apinmo.com/1/2/3.jpg 4444/8888/7777 http://apinmo.com/4/5/8-1.jpg";
我需要删除网址的最后两个斜杠以获取此信息,其余所有保持相同:
And I need to remove the last two slashs of the urls to get this, all the rest remain the same:
$my_NEW_string = "http://apinmo.com/123.jpg 4444/8888/7777 http://apinmo.com/458-1.jpg";
我尝试过:
$my_NEW_string = preg_replace('/(?<=\d)\/(?=\d)/', '', $my_string);
但是我明白了:
$my_NEW_string = "http://apinmo.com/123.jpg 444488887777 http://apinmo.com/458-1.jpg";
在4444/8888/7777
中的斜杠已删除,这不是我所需要的.他们必须留在那里.
The slashes in 4444/8888/7777
where removed and this not what I need. They must to remain there.
更新:由于使用此代码的上下文,我需要这种方法:在"http"和"jpg"之间进行替换
UPDATE: due to the context where this code is used I need this approach: make replacements between 'http' and 'jpg'
推荐答案
这里是执行此操作并保留您的空间的另一种方法:
Here is yet another way to do this and preserve your spaces:
$my_string = "http://apinmo.com/1/2/3.jpg 4444/8888/7777 http://apinmo.com/4/5/8-1.jpg";
$string_array = explode(' ', $my_string);
print_r($string_array); // for testing
$new_array = '';
foreach($string_array AS $original) {
$pos = strpos($original, 'http');
if(0 === $pos){
$new = preg_replace('/(?<=\d)\/(?=\d)/', '', $original);
$new_array[] = $new;
} else {
$new_array[] = $original;
}
}
$new_string = implode(' ', $new_array);
echo $new_string;
返回(注意保留的空格):
Returns (note the preserved spaces):
http://apinmo.com/123.jpg 4444/8888/7777 http://apinmo.com/458-1.jpg
编辑-纯正则表达式方法:
EDIT - Pure regex method:
$new_string = preg_replace('/(?<=\/\d)(\/)/', '', $my_string);
echo $new_string;
返回:http://apinmo.com/123.jpg 4444/8888/7777 http://apinmo.com/458-1.jpg
注意事项:
一种. )即使字符串中没有 空格也能正常工作
2.)如果/
之间的任何数字的长度超过一位数字,则该功能不起作用.
iii. ),如果第二组数字像4444/5/8888
一样,第二个斜杠也将在此处删除.
CAVEATS:
a. ) works even if there are no spaces in the string
2. ) does not work if any number between /
is more than one digit in length.
iii. ) if the second group of digits is like 4444/5/8888
the second slash would get removed here too.
正则表达式的分解方式如下:
Here is how the regex breaks down:
使用正向后匹配以匹配/
后跟数字(?<=\/\d)
我可以断言我要寻找的内容-我只想删除正斜杠 后的正斜杠一个数字.因此,我可以在回溯之后立即使用(\/)
捕获其他正斜杠.无需包含http://
即可启动,也无需包含.jpg
即可退出.
Using a positive lookbehind to match a /
followed by a digit (?<=\/\d)
I can assert what I am looking for - I only want to remove the forward slashes after a forward slash followed by a digit. Therefore I can capture the other forward slashes with (\/)
immediately after the lookbehind. There is no need to include http://
to start or .jpg
to close out.
这篇关于使用PHP替换字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!