php - preg_replace with optional matches -



php - preg_replace with optional matches -

well.. creating blog myself , i've created preg_replace "posts" if type:

[code="php"]foobar[!code]

he prints

<script type="syntaxhighlighter" class="brush: $1; html-script: true"><![cdata[ foobar ]]></script>

everything runs ok preg_replace:

/\[code="(.*?)"\]/

(for prefix)

/\[!code\]/

(for sufix)

but want add together additional alternative check if user has typed... thought that:

[code="php" [1,3]] foo [!code]

return this:

<script type="syntaxhighlighter" class="brush: $1; highlight: [1,3]; html-script: true">...

otherwise if have not $2 (user has typed [code="php"]) homecoming this:

<script type="syntaxhighlighter" class="brush: $1; html-script: true">

how can create statement in same preg_replace? in advance , sry bad english.

edit

i've achieved solution *preg_replace_callback*

you need utilize preg_replace_callback want:

function format_prefix($matches) { homecoming '<script type="syntaxhighlighter" class="brush: ' . $matches[1] . (isset($matches[2]) ? '; highlight: ' . $matches[2] : '') . '; html-script: true">'; } $s = '[code="php"]foobar[!code]'."\n".'[code="php" [1,3]]foobar[!code]'; echo preg_replace_callback('/\[code="(.*?)"(?:\s+(\[\d+,\d+\]))?\]/', 'format_prefix', $s);

php preg-replace

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -