質問

Ok so I'm trying to come up with a PHP method that removes blank bullet point lists that I'm doing.

Here is an example I have:

http://rubular.com/r/01ydqcWx3Q

But I can't seem to get it to only grab the [*] that are blank so I can remove them... This is grabbing the non-blank ones.. so I could put it in the $matches variable below:

preg_match('/\[\*\][A-z0-9 ]+/', $body, $matches);

But.. I want the $matches to consist of the blank ones so I can just remove them.. or if there is a way to grab everything but the matches to remove except for the [list]..

As you can see, it's grabbing the [ in the [/list] which is not what I want either. Some of them will have only two blank, three blank, one blank, or ... more...

Any help would be appreciated.

Thank you!

役に立ちましたか?

解決

If you’d like to match [*] with a regex, you have to escape all three characters with backslashes because they are meta-characters. Next, you have to find out if [*] is immediately followed by a newline (\n or \r\n) or end of list ([/list]). Then replace it with an empty string.

$body = "[list][*]Hydrogen
[*]
[*]Helium
[*]Lithium
[*]
[*]
[*]Beryllium
[*]Boron
[*]Carbon
[*]Nitrogen
[*]
[*]Oxygen
[*][/list]";
$body = preg_replace("/\[\*\](?:\r?\n|(?=\[\/list\]))/", "", $body);
print($body);

The output will be:

[list][*]Hydrogen
[*]Helium
[*]Lithium
[*]Beryllium
[*]Boron
[*]Carbon
[*]Nitrogen
[*]Oxygen
[/list]

他のヒント

Use this to catch strings containing exactly just [*]:

^\[\*\]$

The instruction is then:

preg_replace('/^\[\*\]$/', '', $body);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top