El Blog de Alex Borrás » Posts in 'Funciones' category

Como sustituir - reemplazar un String en PHP

Utilizar la siguiente función:

PHP:
$str = "123,45";
echo str_replace(",",".",$str);
?>

VN:F [1.4.6_730]
Rating: 3.0/5 (1 vote cast)
Posted in Funciones
Tags: ,

Campo de Fecha para formularios PHP

Una función estándar para pedir un campo de fecha en un formulario PHP.

PHP:
/**
 * Devuelve los 3 campos de Fecha: Dia-mes-año
 *
 * @return unknown
 */

function file_date($dia=0,$mes=0,$any=0)
{
    $str ="";
    // Campo día
    $str.="<select name='dia'>";
    $ind = 1;
    while ( $ind <32 )
    {
        $str.= "<option value='$ind";
        if ($dia == $ind)
        {
            $str.="' selected>" ; // Es el día por defecto
        }
        else
        {
            $str.="'>" ;
        }
        $str.="$ind</option>";
        $ind++;
    }
    $str.="</select> ";
    // Campo mes
    $str.="<select name='mes'>";
    $ind = 1;
    while ( $ind <13 )
    {
        $str.= "<option value='$ind";
        if ($mes == $ind)
        {
            $str.="' selected>" ; // Es el día por defecto
        }
        else
        {
            $str.="'>" ;
        }
        $str.= mes_txt($ind)."</option>";
        $ind++;
    }
    $str.="</select> ";
    // Campo any
    $str.="<select name='any'>";
    $ind = 1936;
    while ( $ind <2006 )
    {
        $str.= "<option value='$ind";
        if ($any == $ind)
        {
            $str.="' selected>" ; // Es el día por defecto
        }
        else
        {
            $str.="'>" ;
        }
        $str.= "$ind</option>";
        $ind++;
    }
    $str.="</select>";
    return $str;
}

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones, PHP
Tags: ,

Tratamiento de Fechas en PHP

Obtener por separado el día, mes y año de una Fecha,

PHP:
$date = strtotime("2009-2-27");
echo strftime("%Y",$date);
echo strftime("%d",$date);
echo strftime("%m",$date);

Esta función también es aplicable al valor de un campo leido de una tabla y dejado en una variable

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones
Tags: , ,

Extrar un Tag de un String

Recorrer un string extrayendo una parte del mismo en función de un caracter de apertura y otro de cierre.

Utilizado en Chahoticdocs y Plugin Club de WordPress, especialmente util para los replace de un tag en el $content del WordPress.

Extrae del $content el tag completo y el código del Tag si lo lleva.

Ejemplo de bucle for y recorrer un string tomando caracter por caracter.

PHP:
<?php
$var = club_tag("fñlkjgflkdaj[player=25]fkjñlgakfjd","[player","]");
    if (!$var == false){
        echo $var['fulltag'];
    echo $var['codetag'];
    }
function club_tag($p_content,$p_tag_prefixe,$p_tag_end = "]"){
    $return = array();
    $return['fulltag'] = false;
    $return['codetag'] = false;
    $findcode = false;
    $pos = strpos($p_content,$p_tag_prefixe);
    if ($pos === false){
        return false;
    }
    for ($i = $pos ; $i <= strlen($p_content); $i++){
        $char = substr($p_content,$i,1);
        $return['fulltag'].= $char;
        if ($char == $p_tag_end){
            break;
        }
        if ($findcode){
            $return['codetag'].=$char;
        }
        if ($char == "="){
            $findcode = true;
        }
    }
    return $return;
}
?>

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones, Plugins
Tags: , , ,

PHP: Como saber en que carpeta estamos del servidor

Esto lo he necesitado porque al pasar de PHP 4 a PHP 5 la clase catpcha.php dejo de funcionar, el problema era que no encontraba la ruta de Verdana.ttf.

Lo he solucionado así:

Subo a la carpeta includes el fichero Verdana.ttf

y sustituyo:

define ("FONTNAME", "Verdana.ttf");

por

define ("FONTNAME", dirname (__FILE__)."/Verdana.ttf");

Con esto funciona.

dirname (__FILE__) devuele la carpeta real del disco tipo c:\inetpub\etc... donde está ubicado el archivo que se está ejecutando.

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones
Tags: ,

Ejecutar un programa Windows desde PHP

funcion shell_exec de php.
y que esta función no está habilitada en safe-mode.

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones
Tags:

Equivalencias PHP - Visual Basic

Obtener un fragmento de una Cadena (String)

Visual Basic:

Visual Basic:
Dim MyString As String
MyString = "This is string example"
MsgBox Mid(MyString, 5, 10)

PHP:

PHP:
$MyString = "This is string example";
echo substr($MyString,5,10);

Nota: En ambos casos el contador de caracteres empieza en 0


VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones, Visual Basic
Tags: ,

Separar un String en varias partes

Para separar un string en varias partes en función de un caracter determinado:

PHP:
$string = "Alex;Pedro;Jose;Carlos";
$names = explode(";",$string);
echo $names[0];
echo $names[1];

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones
Tags:

Obtener nombre y extensión de un fichero en PHP

PHP:
<?php
function file_dataname($p_file)
{
    $return = array();
    // Short Name
    $temp = explode("/",$p_file);
    if ($temp[1] == 0)
    {
        $temp = explode("\\",$p_file);
    }
    $temp2 = count($temp) - 1;
    $return['shortname'] = $temp[$temp2];
    // Name WhitoutExtension
    $file = explode(".",$return['shortname']);
    // Usas un for por si el nombre del archivo tiene puntos
    // y no recorres la ultima posicion que se supone tiene la
    // extension del archivos
    for ($i = 0 ; $i <count($file)-1 ; $i++)
    {
            $name.= $file[$i].".";
    }
    // Eliminar el ultimo punto
    $name = substr($name,0,-1);
    // imprimes el nombre o haces con el lo que quieras
    $return['name'] = $name;
    // Extension
    $temp = explode(".",$p_file);
    $temp2 = count($temp) - 1;
    $return['extension'] = $temp[$temp2];;
    return $return;
}

$str = file_dataname("wp-content\alex.borras.php");
echo $str['shortname']."\n";
echo $str['name']."\n";
echo $str['extension']."\n";
?>

VN:F [1.4.6_730]
Rating: 1.0/5 (1 vote cast)
Posted in Funciones
Tags:

Buscar varios Strings dentro de un string

Por ejemplo saber si en un campo de texto han introducido una url (http, www, etc.), esto es útil para evitar robots que nos envían url automaticamente.

En este ejemplo primero se crea una matriz con los string que queremos buscar:

PHP:
function patron_msg() {

   $_msg[] = "href";
   $_msg[] = "http";
   $_msg[] = "www";
   $_patron = "";
   // Se reemplaza en el patron el espacio en blanco por el caracter \040 y se separa con |
   foreach ($_msg as $_msg_item)
   {
       $_patron.= str_replace(" ","\040",$_msg_item)."|";
   }
   $_patron = substr($_patron,0, -1);
   return $_patron;

}

Ahora se comprueba si en el string está algunos de los string que hemos determinado en la función anterior:

PHP:
$_str = "http://www.miweb.com";
   $_patron = patron_msg();
   //Buscar varios string en un string
   if (preg_match("/$_patron_err/i", $_str))
   {
       echo "Encontrado";
   }

El parámetro /i hace que n se tengan en cuenta las diferencias entre mayúsculas y minúculas es decir, si pone HTTP lo encuentra por http.

VN:F [1.4.6_730]
Rating: 0.0/5 (0 votes cast)
Posted in Funciones
Tags: ,