正则表达式以“http并以/结尾”开头?

时间:2013-10-11 08:41:58

标签: php preg-replace

我需要一个替换URL的正则表达式,如下所示:

http://www.domain.com/web/

我试过了:

$pattern = '/\bhttp\S*\/"\b/';

但是不行。

我需要一个开头和结束字符串,它是一个带有

的JSON字符串
"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/obj\/car.png"

"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/"

我需要删除de last:

"ImgRemotePath":"http:\/\/localhost\/\/web\/images\/"

"ImgRemotePath":""

2 个答案:

答案 0 :(得分:1)

这应该是你正在寻找的东西:

<?php
// Subject data
$json = '"ImgRemotePath":"http://localhost/web/images/obj/car.png"';

// First procedure: Using regular expression to match and replace
/* Will match anything except '"' inside the JSON value
 * This limitation means that you should improve the regular expression, if
 * you wish to parse values that includes the '"' character, i.e. improve the
 * regular expression if this is needed, or use the alternative procedure     */
$result = preg_replace('/"ImgRemotePath":"[^"]*"/', '"ImgRemotePath":""', $json);

print $result;

/* Alternative procedure: Decoding, deleting value and encoding back to JSON */
// Convert JSON to associative array
$jsonArray = json_decode('{' . $json . '}', true);

// Set value to empty string
$jsonArray['ImgRemotePath'] = '';

// Cast/encode to JSON
$jsonString = json_encode($jsonArray);

// Remove '{' and '}'
$result = substr($jsonString, 1, strlen($jsonString) - 2);

print $result;

答案 1 :(得分:0)

"http.*/"

尝试这种模式。 基本上,从“http开始,可以有任何字符并以/结尾”