gadss
gadss

Reputation: 22489

Checking a character on a string

How can I check every character on a string on php?

For example I have this string.

$a = "sd qwerty utr";

I want to know the first of the string and get the 1st 3 characters, then I want to get the last 4 characters of the string.

The output will be "sd qwe utr".

Upvotes: 0

Views: 153

Answers (4)

Marius Darila
Marius Darila

Reputation: 873

To produce the output from your example you can try this

<?php
$a = "sd qwerty utr";
$ab=explode(' ',$a);
foreach($ab as $i=>$parts)
$ab[$i]=substr($parts,0,3);
$a=implode(' ',$ab);
echo $a;
?>

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

$a = "sd qwerty utr";

$first=substr($a, 0, 2);

$sec=substr($a, 3, 3);

$third=substr($a, 10, 3);

echo $first." ".$sec." ".$third;

This will give you the desired output....

For more reference check php substr() manual.....

Upvotes: 0

algorhythm
algorhythm

Reputation: 8728

$a = substr($a, 0, 3) . substr($a, -4);

see here: http://php.net/manual/de/function.substr.php

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33511

There are two ways (your question doesn't match your description):

  1. You can use an index to get to each character individually:

    $a = "sd qwerty utr";
    $firstchar = $a[0];
    // etc
    
  2. You can use substr() to get pieces of the string:

    $a = "sd qwerty utr";
    $part = substr($a, 0, 3);    // first 3 chars of string
    

Upvotes: 2

Related Questions