lomboboo
lomboboo

Reputation: 1233

How to match all spaces in the string which starts with

I have HTML with some text and tags. For example,

Outer text with [some random text title="My Title Here"], and more text

I would like to return this html, but replace
1. " for nothing
2. all spaces for  

From the START of title= till ].

So that result of above html will be

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

As I'm using PHP I'd like though to use preg_replace but no idea how to construct corectly search statement.

I've achieved something like this (^title=(.+)]) but this only matches title="My Title Here"] - what I need is to subtract from it spaces and double quotes.

Upvotes: 1

Views: 52

Answers (1)

chris85
chris85

Reputation: 23892

You can use preg_replace_callback and str_replace to accomplish this.

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');

The regex

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

captures everything between title and a ]. For a more detailed explanation see: https://regex101.com/r/cFOYEA/1

Demo: https://eval.in/703649

It also can be done without the capture groups, https://eval.in/703651 (assuming the starting anchor wont have a double quote or space in it).

Upvotes: 2

Related Questions