如何匹配以字符串开头的所有空格

时间:2016-12-23 15:21:49

标签: php regex preg-replace

我的HTML包含一些文字和标签。例如,

"

我想返回此HTML,但替换为 1.   没有
2. title=

的所有空格

]开始直到Outer text with [some random text title=My Title Here], and more text.

以上html的结果将是

preg_replace

由于我正在使用PHP,我想使用(^title=(.+)])但不知道如何构建corectly搜索语句。

我已经取得了类似title="My Title Here"]的内容,但这只匹配$hasSpecialProduct= false; foreach( WC()->cart->get_cart() as $cart_item_key => $values ) { $cart_product = $values['data']; if (in_array($cart_product->id, $array1_ids)) { $hasSpecialProduct = true; } $cart_ids[] = $cart_product->id; } // If one of the special products are in the cart, return true. if ( $hasSpecialProduct ) { echo "true: " , implode(';',$cart_ids);;//bug fixing return true; } else { return false; } - 我需要的是从空格和双引号中减去它。

1 个答案:

答案 0 :(得分:2)

您可以使用preg_replace_callbackstr_replace来完成此操作。

echo preg_replace_callback('/(title=)([^\]]+)/', function($match) {
    return $match[1] . str_replace(array('"', ' '), array('', ' '), $match[2]);
}, 'Outer text with [some random text title="My Title Here"], and more text');

正则表达式

(title=)([^\]]+)

捕获title]之间的所有内容。有关更详细的说明,请参阅:https://regex101.com/r/cFOYEA/1

演示:https://eval.in/703649

也可以在没有捕获组https://eval.in/703651的情况下完成(假设起始锚点中没有双引号或空格)。