1
<?php
$html = "Noticias: <span>PHP 8.3 lanzado</span> y también <span>MySQL 8.4 LTS disponible</span> para servidores.";
// 1. Patrón Codicioso (Greedy): abarcará desde el primer <span> hasta el último </span>
$patronGreedy = '/<span>.*<\/span>/';
// 2. Patrón Perezoso (Lazy): se detendrá en el primer </span> que encuentre
$patronLazy = '/<span>.*?<\/span>/';
echo "<div style='font-family:system-ui; max-width:640px; padding:15px;'>";
echo "<h3 style='color:#0f172a; margin-top:0;'>⚡ Demostración Greedy vs Lazy</h3>";
echo "<p style='color:#64748b; font-size:13px;'>Texto original: <code>" . htmlspecialchars($html) . "</code></p>";
// Prueba 1: Greedy
preg_match($patronGreedy, $html, $matchesGreedy);
echo "<div style='background:#fef2f2; border:1px solid #fecaca; border-left:4px solid #ef4444; padding:12px; border-radius:6px; margin-bottom:12px;'>";
echo " <strong style='color:#991b1b;'>1. Codicioso / Greedy (/<span>.*<\/span>/):</strong><br>";
echo " <span style='color:#64748b; font-size:12px;'>Devoró todo el texto intermedio entre la primera y la última etiqueta:</span><br>";
echo " <code style='color:#b91c1c; font-weight:bold; background:#fff; padding:3px 6px; border-radius:4px; display:inline-block; margin-top:4px;'>" . htmlspecialchars($matchesGreedy[0]) . "</code>";
echo "</div>";
// Prueba 2: Lazy
preg_match_all($patronLazy, $html, $matchesLazy);
echo "<div style='background:#ecfdf5; border:1px solid #a7f3d0; border-left:4px solid #10b981; padding:12px; border-radius:6px;'>";
echo " <strong style='color:#065f46;'>2. Perezoso / Lazy (/<span>.*?<\/span>/):</strong><br>";
echo " <span style='color:#64748b; font-size:12px;'>Aisló correctamente cada etiqueta de forma independiente (" . count($matchesLazy[0]) . " resultados):</span><br>";
foreach ($matchesLazy[0] as $i => $coincidencia) {
echo " <div style='margin-top:4px;'><span style='color:#059669; font-weight:bold;'>[" . ($i+1) . "]</span> <code style='background:#fff; padding:2px 6px; border-radius:4px; color:#047857;'>" . htmlspecialchars($coincidencia) . "</code></div>";
}
echo "</div>";
echo "</div>";
Haz clic para editar este código