1

I have a html content. After i use code like

preg_match('/adm-list-table-cell.*\"del\".*\<\/td/', $content, $zzz);
$new_string = preg_replace('/(\s\/\s)/','',$zzz[0]);
$content = str_replace($zzz[0], $new_string, $content);

for search string / / / / ALL / / / / / / / / / / and delete all / from it. how can i do it with only one preg_replace function? link on regex

revo
  • 47,783
  • 14
  • 74
  • 117
Oleksandr
  • 137
  • 9

2 Answers2

1

The overarching recommendation on StackOverflow for parsing html is to use an html parser like DomDocument. If you provide more information about the variability of your input text, I may be able to write up a refined DomDocument solution.

In the interim, here is a direct, single-pattern preg_replace() call with no unnecessary escaping, minimal capture groups, and greedy character classes for improved efficiency and brevity.

Code: (PHP Demo) (Pattern Demo)

$html = <<<HTML
<td class="adm-list-table-cell align-right"><a href="iblock_element_edit.php?IBLOCK_ID=1&amp;type=news&amp;ID=2&amp;lang=ru&amp;find_section_section=-1&amp;WF=Y" title="title">2</a></td><td class="adm-list-table-cell align-left adm-list-table-cell-last"> /  /  /  / <span class="del">ALL</span> /  /  /  /  /  /  /  /  /  / </td>
HTML;

echo preg_replace('~adm-list-table-cell.*?\K[/ ]*(<span class="del".*?</span>)[/ ]*~', '$1', $html);

Output:

<td class="adm-list-table-cell align-right"><a href="iblock_element_edit.php?IBLOCK_ID=1&amp;type=news&amp;ID=2&amp;lang=ru&amp;find_section_section=-1&amp;WF=Y" title="title">2</a></td><td class="adm-list-table-cell align-left adm-list-table-cell-last"><span class="del">ALL</span></td>

\K is used to "restart" the fullstring match -- so that the preceding element is not destroyed during replacement.

Using lazy quantifiers on the any-character dots (.*?) are important to avoid "flying passed" your targeted substring in your real content.

The forward slashes and spaces are written as a character class with a zero or more quantifier in case the the target substring does not require trimming.

p.s. ...If I can find time to write a DomDocument solution, I'll edit my answer. (but for now I must return to my work)

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

this preg pattern will remove all / in string:

$content = preg_replace('/(adm-list-table-cell[^>]*>)\\s(?:\\/\s+)+(<span class="del".*<\\/span>)\\s(?:\\/\\s+)+(<)/', '${1}${2}${3}', $content);

https://regex101.com/r/yCDvKE/2