Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Feb 2010
    Messaggi
    333

    Un pattern regex per sostituire alcuni tags

    Ciao a tutti
    ho fatto 3 patterns regex per sostituire alcuni tags html in una frase
    La frase è:

    $frase="<h2>Ciao come stai?</h2><h2>Spero che tu stia bene</h2>";

    Di questa frase io desidero sostituire nulla "" al primo <h2>, "->" al gruppo </h2><h2> e un punto a'ultimo </h2>

    Per fare questo ho fatto:

    $patterns = array();
    $patterns[0] = '/<h2>/';
    $patterns[1] = '/<\/<h2><h2>/';
    $patterns[2] = '/<\/h2>/';
    $replacements = array();
    $replacements[2] = '';
    $replacements[1] = '.';
    $replacements[0] = '->';
    preg_replace($patterns,$replacements,$frase);

    Ma mi sostiruisce a casaccio

    (so che i due array sono invertiti come leggo nel manuale ma li ho provati anche non inveriti tra dì loro)

    PS
    Non si riesce con un solo pattern?

  2. #2
    Utente di HTML.it L'avatar di homerbit
    Registrato dal
    Dec 2005
    residenza
    Roma
    Messaggi
    1,380
    così può andar bene?
    Codice PHP:
    <?php
    $frase
    ="<h2>Ciao come stai?</h2><h2>Spero che tu stia bene</h2>";
    $frase_1 str_replace("</h2><h2>""->""$frase");
    $frase_2 str_replace("</h2>"".""$frase_1");
    $frase_3 str_replace("<h2>""""$frase_2");
    echo 
    $frase_3;
    ?>
    potresti anche annidarli anche se perderesti leggibilità del code
    If you think your users are idiots, only idiots will use it. DropBox

  3. #3
    Utente di HTML.it
    Registrato dal
    Feb 2010
    Messaggi
    333
    Originariamente inviato da homerbit
    così può andar bene?
    Codice PHP:
    <?php
    $frase
    ="<h2>Ciao come stai?</h2><h2>Spero che tu stia bene</h2>";
    $frase_1 str_replace("</h2><h2>""->""$frase");
    $frase_2 str_replace("</h2>"".""$frase_1");
    $frase_3 str_replace("<h2>""""$frase_2");
    echo 
    $frase_3;
    ?>
    potresti anche annidarli anche se perderesti leggibilità del code
    Si infatti attualmente ho fatto anche così:

    $pat="/<\/h2><h2>/i";
    $pat1="/<\/h2>/i";
    $pat2="/<h2>/i";
    preg_replace($pat2,"",preg_replace($pat1,"...",pre g_replace($pat,"->",$frase)))

    Ovvero con le preg_replace nidificate.

    Io però vedo (ma non riesco ad applicarlo) che si può usare un pattern soltanto del tipo:

    $pat="/\B(<\/h2><h2>|<\/h2>|<h2>)\B/i";
    il quale in match all mi da un array dei 3 gruppi di tags che però non riesco ad applicare con un preg_replace solo

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.