Funciones String

12 mayo, 2008 · Alex Borrás
El Blog de Alex Borrás · https://alexborras.com/funciones-string/

Funciones de tratamiento de String en PHP:

Pasar String a minúsculas

$str = "Hola esto es UNion";
$str = strtolower($str);

strong>Buscar un String dentro de otro

Distinguiendo Mayúsculas de minúsculas

$str = "Hola esto es UNION";
if (strpos($str,"UNION") > 0)  ...

Sin distinguir (solo en PHP5):

$str = "Hola esto es UnIoN";
if (stripos($str,"UNION")
...

Obtener la posición de un String dentro de otro

<code><span style="color: #000000;"><span style="color: #0000bb;">
&lt;?php
$mystring </span><span style="color: #007700;">= </span><span style="color: #dd0000;">'abc'</span><span style="color: #007700;">;
</span><span style="color: #0000bb;">$findme </span><span style="color: #007700;">= </span><span style="color: #dd0000;">'a'</span><span style="color: #007700;">;
</span><span style="color: #0000bb;">$pos </span><span style="color: #007700;">= </span><span style="color: #0000bb;">strpos</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$mystring</span><span style="color: #007700;">, </span><span style="color: #0000bb;">$findme</span><span style="color: #007700;">);</span></span></code>

<span style="color: #ff8000;">// Note our use of ===.  Simply == would not work as  expected
// because the position of 'a' was the 0th (first)  character.
</span><span style="color: #007700;">if (</span><span style="color: #0000bb;">$pos </span><span style="color: #007700;">=== </span><span style="color: #0000bb;">false</span><span style="color: #007700;">) {
echo </span><span style="color: #dd0000;">"The string '$findme'  was not found in the string '$mystring'"</span><span style="color: #007700;">;
} else  {
echo </span><span style="color: #dd0000;">"The string '$findme' was found in the  string '$mystring'"</span><span style="color: #007700;">;
echo </span><span style="color: #dd0000;">" and exists at position $pos"</span><span style="color: #007700;">;
}</span>

<span style="color: #ff8000;">// We can search for the  character, ignoring anything before the offset
</span><span style="color: #0000bb;">$newstring </span><span style="color: #007700;">= </span><span style="color: #dd0000;">'abcdef abcdef'</span><span style="color: #007700;">;
</span><span style="color: #0000bb;">$pos </span><span style="color: #007700;">= </span><span style="color: #0000bb;">strpos</span><span style="color: #007700;">(</span><span style="color: #0000bb;">$newstring</span><span style="color: #007700;">, </span><span style="color: #dd0000;">'a'</span><span style="color: #007700;">, </span><span style="color: #0000bb;">1</span><span style="color: #007700;">); </span><span style="color: #ff8000;">// $pos  = 7, not 0
</span><span style="color: #0000bb;">?&gt;
</span>