Reaper Music
Reaper Music

Reputation: 115

How can I replace all even matches of a word in a string?

I am trying to convert Remarkup to MediaWiki markup.

In Remarkup, code blocks use the following syntax:

```
some code
```

I would like to replace that with MediaWiki's code block syntax, which is as follows:

<code>
some code
</code>

As you can see, I can't just use preg_replace() for this, since odd occurrences (of ```) should be replaced with <code> and even occurrences with </code>.

How can I do this in PHP?

Upvotes: 1

Views: 313

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You should use a markdown parser to do that.

ParseDown is only one of the multiple choices out there:

$parsedown = new Parsedown();

echo $parsedown->text('
```
some code
```
');

The result would be: <pre><code>some code</code></pre>

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

Define custom replacement logic as a callback for preg_replace_callback, something like:

$count = 0;
$s1 = preg_replace_callback(
    '/```/', 
    function($m) use (&$count) { ++$count; return $count % 2 ? '<code>' : '</code>'; },   
    $s
);

Upvotes: 7

Related Questions