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

Asked

Viewed 732 times

10

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

I was wearing 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 then in HTML:

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

But then the texts increased a lot, and I wondered if it is not possible to do a function with preg_replace or something like that, that went through the files behind the texts, without needing to always include the function in HTML...

Basically, the file is 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 to summarize I have two types of text to exchange: O cliente and o cliente, respectively to A cliente and a cliente.

Is there a way to do this? How?

  • 1

    you can use a placeholder defined with, for example, two brackets: $texto = "Loren ipsum [[o]] cliente", utilise str_replace('[[o]]', mudasexo($sexo), $texto) and str_replace('[[O]]', mudasexocaps($sexo), $texto)

  • Use a view. It’s easier! See my answer ;)

4 answers

14


Initial idea:

I used a small text, but this fits perfectly for a full HTML page. It follows a sketch of what you can do, in a very simple way:

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

See working on IDEONE.


If you need to change several words (it is 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 have how to make a replace. Just leave a special marking in 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 substitution after the text already exists. In the previous ones, we merge the text after defining the variables.


The same technique can be used for upper and lower case, just 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 from a array associative the desired words:

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

Example of use:

$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 on IDEONE.


Using what PHP already has "embedded":

This syntax is more confusing for long lists of words, but the str_replace PHP 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 );

Again, see working on IDEONE.


Notes:

  • In the first examples, we are using PHP’s own variable substitution.

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

    I used the character #, but it could be anything else that makes your job easier, as long as it’s a string that does not match any actual text information that should not be replaced. If we used [batata] and [pipoca], would still.

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

  • 2

    Excellent reply @Bacco! It looks much simpler and more efficient than it had been doing... But just so I understand a point, so there’s really no way to scan the HTML code (which is included by include on the PHP page, find where it is written caro cliente (no appointments), and if the sex is female, change to cara cliente? (is that are many files... rsrs) Thank you very much! + 1

  • 4

    @Gustavox can trade anything you want, 'expensive' for 'expensive' or 'expensive', 'friend' for 'friend' or 'friend', but the side effects will give you more trouble than you think. There will be situations where the 'expensive' will be part of other words, and will be improperly exchanged. Even though it’s a lot of pages, I’m sure the time you’re going to waste with brands is less than patching ;)

  • 3

    @gustavox think fondly of the "marked" version:) Yours does not fail to be marked, the problem is the chance of confusion. And there’s more: If it’s a few words, you might as well give one search & replace in its sources, exchanging "The Complainant" for "#Complainant#" on all pages, with a code editor (automatically), and so on with the other keywords.

  • 2

    The good thing about you giving the search and replace is that, from "toast", you will already detect the possible problems you would have without the markups. And a suitable search & replace example: "The client" replace with "#OA# client" (using the word client as "anchor" so as not to replace the wrong "O"s)

  • So, just for the record, it came out right here. I used ob_start and ob_get_clean to create the variable $texto in the archive principal.php, and worked perfectly. I used the solution with the #oa#, and searched and replaced all files by the IDE in a matter of microseconds. : ) I was just wondering if I might have performance problems, since he is scanning the entire rendered file before printing on the screen, but I haven’t run any tests yet, and I think that’s another story. : ) Thank you very much!

  • 2

    This is the foundation of a template system. I was going to suggest that @gustavox should use one, but this is simple, it takes care of it and most of all, it’s not a black box. + 1

Show 1 more comment

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.

  • In case I used with ob_start and ob_get_clean to create the variable, but it was basically this solution that I used, only as a simple function (so I could put other rules...), the second that Bacco posted. Of .

1

When it comes to variable texts mixed with static text, the best solution would be to use a view (or something similar) ?

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 that will be loaded by the function view.

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 way out in this case will be:

the customer is always above all!

I’d rather do something like that, since it makes a view totally reusable.

There would still be a third option, which is using a Closure in this parameter.

Thus:

$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 both O cliente, as A cliente, depending on the given parameter.

  • Interesting solution. + 1

0

You better 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 like. The $a variable should only be used when the word changes in feminine only. Another thing, remember to escape the dollar ($) when you want to actually use it in the text. Example:

$textoOriginal  = '$O senhor$a deve R\$ 20,00...';
$textoFinal     = acertaTexto( $textoOriginal );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.