E
E
exxagw2015-12-11 02:59:35
PHP
exxagw, 2015-12-11 02:59:35

How to write a complex regexp condition?

How to turn it

<chunk></chunk>
<chunk></chunk>
<chunk></chunk>

in it?
<span data-element="chunk" name="chunk.name.test"></span>
<span data-element="chunk" name="tpl.test.name"></span>
<span data-element="chunk" name="test"></span>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2015-12-11
@exxagw

<?php

$str = '<chunk></chunk><chunk></chunk><chunk></chunk>';
$replace = '<span data-element="$1" name="$3">$2</span>';

echo preg_replace("/<(\w+)>(\[\+)\]\])<\/(\w+)>/u", $replace, $str);

Conclusion:
$ php replace.php
<span data-element="chunk" name="chunk.name.test"></span>
<span data-element="chunk" name="tpl.test.name"></span>
<span data-element="chunk" name="test"></span>

$allow option:
<?php

$str = '<chunk></chunk><chunk></chunk><chunk></chunk>';
$replace = '<span data-element="$1" name="$3">$2</span>';
$allow = 'chunk.name.test|test';

echo preg_replace("/<(\w+)>(\[\[[$!]+((?:{$allow}))\]\])<\/(\w+)>/u", $replace, $str);

Conclusion:
$ php replace.php
<span data-element="chunk" name="chunk.name.test"></span>
<chunk></chunk>
<span data-element="chunk" name="test"></span>

Play around here:
https://regex101.com/r/gI5rE3/1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question