May 9, 2013

What is the best way to prepend a conjunction to the end of an imploded array in PHP?

Danronmoon’s Questions:

Let’s say I have an array.

$shopping_list = array('eggs', 'butter', 'milk', 'cereal');

What is the easiest and/or most clever way to display this as a comma-delimited list and prepend a word (conjunction, preposition, etc.) to the last value? Desired results include:

'eggs, butter, milk, and cereal'
'eggs, butter, milk, or cereal'
'eggs, butter, milk, with cereal'
'eggs, butter, milk, in cereal'
// etc.

The array will be of variable length, may be associative, and preferably it shouldn’t be modified. It needn’t be imploded either; I figure this is just the standard way of doing things like this. Array dereferencing is fine too, but something PHP 5.3-compatible would be great.

I’m thinking something along the lines of

$extra_word = 'and';

implode(', ', array_slice($shopping_list, 0, count($shopping_list) - 1)) 
    . ', ' . $extra_word . ' '
    . implode(',', array_slice($shopping_list, count($shopping_list) - 1));

But that’s a doozy. Loops are cleaner and slightly less inept:

$i = 0;
$output = '';

foreach ($shopping_list as $item) {
   $i += 1;
   if ($i > 1) {
       $output .= ', ';
       if ($i === count($shopping_list)) {
           $output .= $extra_word . ' ';
       }
   }

   $output .= $item;
}

Both of these ways seem roundabout. Is there a better way out there that comes to mind?

This is cleaner too.

$pop = array_pop($shopping_list);
echo implode(", ", $shopping_list)." and $pop.";
November 6, 2012

How to dynamically create a string in PHP?

Question by All

I have a predefined pattern for building a string, which should be created regularly throughout the script.

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

Currently, I am using eval to generate the string in place based on the pattern originally defined. However, as this happens occasionally and eval is generally bad, I wish to find another method.

NOTE that the pattern is defined only one time above all codes, and I can edit the pattern of all the script by one line only. Thus, what makes $string should not be touched for any change.

I tried create_function, but needs the same number of arguments. With eval, I can easily change the pattern, but with create-function, I need to change the entire script. For example, if changing the string pattern to

$str="$first @@ $second"; // One arg/var is dropped

eval Example:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("$string = "$str";");

create_function Example:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);

Answer by Vulcan

You can use the string formatting capabilities offered by sprintf or vsprintf.

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

You can use vsprintf if you wish to pass an array.

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);

Answer by Starx

Seems to be rather simple thing to me. Use str_replace() and replace based on patterns

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);
October 13, 2012

Check whether an input string contains number

Question by Udara S.S Liyanage

I want to check whether an input string contains number.

I am trying to validate an input field. I want it to contain only alphabet, not numbers.

Answer by Starx

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/d+/g);
if (matches != null) {
    alert('number');
}
August 16, 2012

Difference between   and  

Question by Ketan

Can any one explain me difference between   and   ?

I have html data stored in database in binary form and space in that can be either of   or   or sometimes  .

Also issue is when I convert this HTML to plain text using JSoup lib it is converting it properly but if I use String.contains(my string) method of java. It looks like the HTML data which is having   is different from which is having  . String is not found in either vice versa.

Example:

HTML1 : This is my test string

HTML2 : This is my test string

If I convert it to plain text using JSoup. It returns

HTML 1 : This is my test string

HTML 2 : This is my test string

But still both string are not same. Why is it so?

Answer by strnk

  is the classic space, the one you get when you hit your spacebar, represented by his HTML entity equivalent.

  and   represents the non-breaking space, often used to prevent collapse of multiple spaces togethers by the browser :

"    " => ” ” (collapsed into only one space)

"    " => ”    ” (not collapsed)

If you are parsing a string containing both classic and non-breaking spaces, you can safely replace one by the other.

Answer by Starx

 , is just a space character nothing more. Regular occurrence of this character will collapse to one space character at the end.

Where as &#160 and   both represent non-breaking space character and if they occur continuously one after another, they will be collapse or break to one space character.

Only, difference between them is that &#160 is the HTML number and   is a HTML name.

Basically all of these are HTML entities. You can learn and know about them, seeing the following links.

  1. Link 1
  2. Link 2
July 18, 2012

PHP echo part of a string from right to left

Question by shwebdev

I am trying to get the ID from the end of this string the 4305 after the -. The code below works from left to right and shows 150. How can i make it work from right to left to show the 4305 after the -?

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = substr($mystring, 0, strpos($mystring, "-"));
  echo $mystring;

Updated: This does what i need but i’m sure there is a better way to write it:

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = substr(strrev($mystring), 0, strpos(strrev($mystring), "-"));
  echo strrev($mystring);

Answer by Michael Mior

You can use strrpos to get the last hyphen in the string, and then take the rest of the string after this character.

$mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
$mystring = substr($mystring, strrpos($mystring, "-") + 1);
echo $mystring;

Answer by Starx

Most easiest way is definitely using explode.

By using explode, you can split the string into an array with each parts accessible as individual identifiers using the indexes.

Usage Example:

  $mystring = "150-Adelaide-Street-Brisbane-Cbd-4305";
  $mystring = explode("-", $mystring);
  echo $mystring[count($mystring)-1]; //Extract the last item
April 14, 2012

Why is my array.length returning such a high number?

Question by Trey

For some reason I can push JSON objects to my array “list”, but when I call its .length, it seems that I’m getting the number of characters rather than number of items.

UPDATE: See answers for solution. My script wasn’t returning characters, it was looping through exponentially.

$.getJSON('[omitted].php?callback=?',function(d,item){
    var list = []
    alert('Length: '+d.length) // d consists of 271 JSON objects, d.length = 271
    for (i=0;i<d.length;i++){
        $.each(d,function(){ // for each JSON object we add...
            list.push({'name':this.name,'href':this.href,'img':this.img})
        })
        if (i==d.length){
        alert('Completed - Length: '+list.length) // list.length = 44711. Why?
        }
    }
})

Note that when I use alert(list) I see:

[object,Object][object,Object][object,Object] ...

Rather than an array:

[[object,Object][object,Object][object,Object] ... ]

Answer by am not i am

I believe this…

$.each(d,function(){

should be this…

$.each(d[i],function(){

Otherwise you’re looping over the same d structure once for every item in d.

Answer by Starx

Lets see, the basic structure of a each statement

$.each(mixedVar, function(index, item) {
     //Here index, is not an array but singular item's index, so whenever
     // index.length will be applied it will be taken as a variables, that a list/collection/array
});

In the same way, your d is also returning a item’s index, which is a mixed variable, neither a list nor an array.

April 12, 2012

How to use PHP string in mySQL LIKE query?

Question by John Robinson

I am trying to find the number of rows that match a specific pattern. In this example, all that START with “123”:

This is working:

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);

The problem is the LIKE will vary, so I’m trying to define it in the script, then execute the query, but this is NOT working:

$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);

How can I get this query to work properly in the second example?

EDIT: I’ve also tried it without the period (also not working):

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");

Answer by Jon

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it’s not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Answer by Starx

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

April 5, 2012

echo plus sign php

Question by jose

I’m echoing a php string variable into html

<span class="title_resource">
  <?php echo  $titulo; ?>
</span>

But when the plus sign (+) is present, it turns into a space.

I’ve already tried using urlencode but then I get something like “Constru%25C3%25A7%25C3%”

Should I use something like string replace?

Thanks in advance

Update:

$titulo is setted using $_GET

if (isset($_GET['T']))// title
    $titulo = $_GET['T'];

(…)

More clear, perhaps

I want to send exactly this text “Estudo de ax^2 + bx + c”. The page receives by $_GET. When I print this value I get “Estudo de ax^2 bx c”

Answer by Starx

Its the way values as encoded to be sent over using GET, spaces are converted to + and + are converted to %2B.

If you really want to send the plus symbol over the form, then replace the spaces with plus

$text= str_replace(" ", "+", $text);

Next make sure your form uses correct enctype either application/x-www-form-urlencoded or multipart/form-data

April 2, 2012

How to remove ANSI-Code ("&#13;") from string in PHP

Question by ESCOBAR

I have tried a lot but nothing is working. I want to import a XML-file with PHP. In some strings the customer puts some ANSI-Code Carrier Returns (“&#13;”). I have tried to remove them with:

str_replace('r', '', $xml->description);

I also tried it with "&#13;", "rn", "&\#13;" in the search but nothing works. Do you have any idea how to remove these linebreaks?

Thanks!

Answer by Corbin

Since your XML processor is already handling de-entitying the entities, you’ll be left over with plain ASCII n or r or rn. PHP does not handle r or n inside of single quotes. It only translates them to their respective characters (codes 10 and 13), when the r and n are inside of double quotes.

You just need to use “n” or maybe “rn”.

Answer by Starx

Actually, This runs just fine

$str = "&#13;"; //just an example

echo str_replace("&\#13;", "hello", $str);

Demo

March 28, 2012

What does '" actually mean in PHP Syntax?

Question by Christus Cleetus

I have a piece of code and i keep getting syntax errors for codes like thess :

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";

Now when i reformat it as :

$query ="SELECT * from `jos_menu` where `id` = ".$parent;

That is when i remove : ‘”
it works fine. So i am just wondering, what does (‘”) actually do ???

Answer by Burhan Khalid

The only problem with

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";

Is that you missed a few ':

$query ="SELECT * from `jos_menu` where `id` = ".'"'.$parent.'"';

In PHP, a string can either be:

$var = 'This is a string';

Or

$var = "This is a string";

If you want to put " inside a string that you already started with ", you need tell PHP that you don’t want your second " to end the string but use the character " as part of the string itself. This is what " does. It tells PHP that Don’t give the " character any special meaning; since normally if you started the string with ", the next " would end the string.

means remove any “special” meaning to the next character

This only works if the character after the would have had special meaning. Some examples:

Suppose we want to print Hello "World". I am a string!:

$var = "Hello "World". I am a string!";

In this example we will have errors. Since we started the string with ", the next " will close the string. So what PHP thinks:

  1. " Start of string
  2. Hello part of string variable.
  3. " Hey, since I saw that the string was started with ", this must mean the end of it!
  4. World" <– Error

Stop processing and throw errors.

However, if we write:

$var = "Hello "World". I am a string!";

Now, PHP thinks:

  1. " Start of string
  2. Hello part of string variable
  3. Ah, okay, the next character I should remove any special meaning
  4. " Okay, this is immediately after , so I just use it normally, as a ".
  5. World part of string
  6. Okay, the next character I will remove any special meaning
  7. " This is now a normal "
  8. . I am a string! – part of string variable.
  9. " Ah! Since the string was started with ", this must be the ending.
  10. ; ends statement.

Hopefully this clarifies things for you.

Answer by Starx

It denotes escaped characters. The next character that appear after it, will be taken as its current form.

Your Query is incorrectly escaped

$query ="SELECT * from `jos_menu` where `id` = ".'".$parent.'";
                                               //^ You mismatched the quotes from here

A correctly escaped query should be

$query ="SELECT * from `jos_menu` where `id` = "$parent"";
                                           //  ^ Note here " will printed as it is within the query

For example,
If $parent was 2, then the query would be

 SELECT * from `jos_menu` where `id` = "2"
...

Please fill the form - I will response as fast as I can!