How to create a function to page dynamically created PHP page and change certain text

10

I have a PHP page that is dynamically mounted, and I need to change certain texts, depending on the user being male and female.

I was using it like this:

function mudasexocaps($sexo) {

    if ($sexo == "feminino") {
        echo "A";
    }
    else {
        echo "O";
    }
}

function mudasexo($sexo) {

    if ($sexo == "feminino") {
        echo "a";
    }
    else {
        echo "o";
    }
}

And here's the HTML:

<p><?php mudasexocaps($sexo) ?> cliente ?> ></p>

But the texts have increased a lot, and I was wondering if it is not possible to do a function with preg_replace or something like that, to go through the files behind the texts, without needing to include the function in HTML every time. .

Basically, the file looks like this:

main.php

(a função acima)
include texto1.php
include texto2.php
etc..

texto1.php

<p>O cliente ipsum dolor sit amet, consectetur adipiscing elit. Proin hendrerit accumsan lacus eget luctus. Ut ligula mi, ullamcorper quis diam sed, cursus gravida sem.</p>

texto2.php

<p> Loren ipsum o cliente dolor sit amet, consectetur adipiscing elit. Proin hendrerit accumsan lacus eget luctus. Ut ligula mi, ullamcorper quis diam sed, cursus gravida sem.</p>
So I have two types of text to change: O cliente and o cliente , respectively for A cliente and a cliente .

Is there a way to do this? As?

    
asked by anonymous 11.11.2015 / 18:28

4 answers

14

Initial idea:

I used a little text, but this is fine for a full HTML page. Here's an outline of what you can do, quite simply:

$oa = ( $sexo == "feminino" )? 'a':'o';
$texto  = "Olá, car$oa cliente!\n";
$texto .= "Seja bem-vind$oa à nossa central de atendimento!\n";

See working at IDEONE .


If you need to change multiple words (case sensitive):

if ( $sexo == "feminino" ) {
   $oa = 'a';
   $hm = 'mulheres';
} else {
   $oa = 'o';
   $hm = 'homens';
}

$texto  = "Olá, car$oa cliente!\n";
$texto .= "Seja bem-vind$oa à nossa central de atendimento para $hm!\n";


If the text comes ready, from another place or template, you can do a replace . Just leave a special mark on the original text:

$texto  = "Olá, car#oa# cliente!\n";
$texto .= "Seja bem-vind#oa# à nossa central de atendimento para #hm#!\n";

if ( $sexo == 'feminino' ) {
   $texto = str_replace ( '#oa#' , 'a'       , $texto );
   $texto = str_replace ( '#hm#' , 'mulheres', $texto );
} else {
   $texto = str_replace ( '#oa#' , 'o'     , $texto );
   $texto = str_replace ( '#hm#' , 'homens', $texto );
}

Note that this time we do the replacement after the text already exists. In the previous ones, we merge the text after defining the variables.


The same technique can be used for uppercase and lowercase letters, you would have to define, for example #oa# and #OA# in the templates.


Applying the concepts in a more complete function:

With this function, we do the str_replace in a loop , taking an associative array the desired words:

function substituir( $texto, $arr ) {
   foreach ($arr as $key => $value) {
      $texto = str_replace ( $key, $value, $texto);
   }
   return $texto;
}

Example usage:

$texto  = "Olá, car#oa# cliente!\n";
$texto .= "Seja bem-vind#oa# à nossa central de atendimento para #hm#!\n";

$masculino = array( '#oa#' => 'o', '#hm#' => 'homens'   /*, etc */ );
$feminino  = array( '#oa#' => 'a', '#hm#' => 'mulheres' /*, etc */ );

$texto = substituir( $texto, $sexo == 'feminino' ? $feminino : $masculino );

See working at IDEONE .


Using what PHP already has "embedded":

This syntax is more confusing for long word lists, but PHP str_replace also accepts arrays , eliminating the need for an extra function:

$texto  = "Olá, car#oa# cliente!\n";
$texto .= "Seja bem-vind#oa# à nossa central de atendimento para #hm#!\n";

$placeholders = array( '#oa#','#hm#'     /*, etc */ );
$masculino    = array( 'o'   ,'homens'   /*, etc */ );
$feminino     = array( 'a'   ,'mulheres' /*, etc */ );

$texto = str_replace( $placeholders, $sexo=='feminino'?$feminino:$masculino, $texto );

Once again, check out IDEONE .


Notes:

  • In the first few examples, we are using PHP's own variable override.

  • In the second case, I used the symbols #oa# and #hm# , in a similar way to the suggestion that the user @ Sançao made in comments .

    I used the # character, but it can be anything else that makes your work easier, as long as it is a string that does not match some real text information that should not be replaced. If we used [batata] and [pipoca] , it would be the same.

  • In principle, no need for multibyte functions. If you use the same encoding in $texto and in array values, encoding is irrelevant since the literal search will always work.

  • >
11.11.2015 / 21:41
2

Dear Gustavox, see if this would help you:

$texto1 = file_get_contents('texto1.php');
echo str_replace('O Cliente','A Cliente',$texto1);

You can even change str_replace and create your own function. Note: This is just a small example.

    
17.11.2015 / 14:15
1

When dealing with variable text mixed with static text, would the best solution be to use a view (or something like that)?

I'll create a simple view for you to understand.

Example:

function view($view, array $data)
{
   unset($view, $data); // Por causa da colisão de nomes do extract

   ob_start();

   extract(func_get_arg(1));

   include func_get_arg(0);// Equivale ao caminho da view  

   return ob_get_clean();

}

Create the page to be loaded by the view function.

Example pagina.php :

<div><?=$_client?> está sempre acima de todos!</div>

You could generate two different pages just by doing so:

echo view('pagina.php', array('_cliente' => 'a cliente'));

echo view('pagina.php', array('_cliente' => 'o cliente'));

The output in this case will be:

the customer is always above all!

I'd rather do something of the sort, since that makes a view completely reusable.

I would still have a third option, which is using Closure in this parameter.

So:

$sexo = $_GET['sexo']; // Apenas um exemplo 

$closure = function($sexo)
{
   if ($sexo == 'M') {
       $cliente = 'O cliente';
   } else {
      $client = 'A cliente';
   }

   return $cliente;
};

view('pagina.php', array('_cliente' => $closure, 'sexo'=> $sexo));

pagina.php

<div>Chamando como função anônima <?=$_client($sexo)?> que sempre acima de todos!</div>

The result could be either O cliente , or A cliente , depending on the given parameter.

    
18.11.2015 / 20:55
0

It's good for you to simplify the code. See the example below:

<?php

function acertaTexto( $texto, $sexo = 'masculino' ) {
    if ( $sexo === 'masculino' ) {
        $Ao = 'Ao';
        $ao = 'aa';
        $O  = 'O';
        $o  = 'o';
        $a  = '';
    }
    else {
        $Ao = 'À';
        $ao = 'ao';
        $O  = 'A';
        $o = 'a';
        $a = 'a';
    }
    eval( '$retorno = "' . $texto . '";' );
    return $retorno;
}
$textoOriginal  = '$Ao senhor$a Fulano! $O senhor$a pode comparecer...';
$textoFinal     = acertaTexto( $textoOriginal );

Then you can configure your text as you want. The variable $ a should only be used when the word modify only in the feminine. Another thing, remember to escape the dollar sign ($) when you actually want to use it in the text. Example:

$textoOriginal  = '$O senhor$a deve R\$ 20,00...';
$textoFinal     = acertaTexto( $textoOriginal );
    
08.12.2015 / 14:21