unexpected output of ltrim in php - php

Can anybody explain this unusual output of ltrim
var_dump(ltrim('/btcapi/participation/set-user-event-participation','/btcapi'));
rticipation/set-user-event-participation //output
While expected output has
/participation/set-user-event-participation

Use str_replace if you are sure this is the only one occurence in your string.
$str = '/btcapi/participation/set-user-event-participation';
echo str_replace('/btcapi', $str); // returns: '/participation/set-user-event-participation'
Or regex if you need replace/remove just the first at the beginning of string.
$str = '/btcapi/participation/set-user-event-participation';
preg_replace ('~^/btcapi~', '', $str);

The trim characters are read as individuals, not as a String.
It just replaces the second / for example because it is a part of the characters.
Just use str_replace or a custom loop.

RTM: http://php.net/ltrim
the second argument is a character MASK, e.g. characters you want to strip. CHARACTERS, not STRING.
php > $foo = 'abc123';
php > echo ltrim($foo, 'abpq');
c123
php > echo ltrim($foo, 'a1');
bc123
^---not stripped, because 'bc' are not in the mask.
php >
PHP will search strip all characters from the left of the string, based on the characters in the mask, until it encounters a character NOT in the mask.

Related

php: I want to trim "h;" from "w;h;" to get ''w;' but what I got is "w"

The below program is to right trim the string "w;h;" off string "h;" to get "w;". But unexpectedly what I got is "w", not "w;".
<?php
$string="w;h;";
$str="h;";
$nStr=rtrim($string,$str);
echo $nStr.'</br>';
?>
Use str_replace http://php.net/manual/en/function.str-replace.php
$string="w;h;";
$str="h;";
Echo str_replace($str, "", $string);
https://3v4l.org/P9Hbe
Str_replace replaces $str with nothing. Leaving w;
From the manual:
character_mask
Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
If you do rtrim("w;h;", "h;") you're saying "trim either h or ; from the end of the string, meaning cut off characters that are either h or ; in this case it will cut off characters until it is only left with w.
If you want to remove a specific string from the end you have to do something like:
if (substr($string,-strlen($str)) == $str) {
$string = substr($string,0,-strlen($str));
}
Note: This assumes ASCII strings. For UTF-8 multibyte strings use mb_substr .

Separate Unicode and Ascii Charactors with White Space from PHP

I'm Doing some class to Handle Sinhala Unicode from php, I want to separate mixed string Unicode and ascii char as a separate words with white space.
example:
$inputstr = "ලංකාABCDE TEST1දිස්ත්‍රික් වාණිජ්‍යTEMP මණ්ඩලය # MNOPQ";
function separatestring($inputstr)
{
//do some code
return $inputstr;
}
echo separatestring($inputstr);
//OUTPUT String = ලංකා ABCDE TEST1 දිස්ත්‍රික් වාණිජ්‍ය TEMP මණ්ඩලය # MNOPQ
i have try with preg_replace with Regex and several looping methods but any method did not success. please help me on this. Thanks All!
This works for me:
$inputstr = "ලංකාABCDE TEST1දිස්ත්‍රික් වාණිජ්‍යTEMP මණ්ඩලය # MNOPQ";
function separatestring($inputstr)
{
$re = '#\s+|(?<=[^\x20-\x7f])(?=[\x20-\x7f])'
. '|(?<=[\x20-\x7f])(?=[^\x20-\x7f])#';
$array = preg_split($re, $inputstr);
return array_filter($array);
}
echo implode(" ", separatestring($inputstr));
//OUTPUT String = ලංකා ABCDE TEST1 දිස්ත්‍රික් වාණිජ්‍ය TEMP මණ්ඩලය # MNOPQ
The regexp for splitting means the following:
# — start regexp (delimeter character),
\s+ — split on one or more whitespace character (counting the whitespace as the separator),
| — or,
(?<=[^\x20-\x7f])(?=[\x20-\x7f]) — split on a border between non-ASCII and ASCII characters (not counting them as separators),
| — or,
(?<=[\x20-\x7f])(?=[^\x20-\x7f]) — split on a border between ASCII and non-ASCII characters (not counting them as separators),
# — end regexp (delimeter character).
Unfortunately, my regular expression is not too elegant, so sometimes the empty strings are returned (because whitespace is also an ASCII character). I’ve put array_filter to fix this, but a more elegant solution might exist.
I’ve written separatestring in such a way that it returns in array. If you want a string, replace the return statement this way:
return implode(" ", array_filter($array));

How to match alphanumeric and symbols using PHP?

I'm working with text content in UTF8 encoding stored in variable $title.
Using preg_replace, how do I append an extra space if the $title string is ending with:
upper/lower case character
digit
symbol, eg. ? or !
This should do the trick:
preg_replace('/^(.*[\w?!])$/', "$1 ", $string);
In essence what it does is if the string ends in one of your unwanted characters it appends a single space.
If the string doesn't match the pattern, then preg_replace() returns the original string - so you're still good.
If you need to expand your list of unwanted endings you can just add them into the character block [\w?!]
Using a positive lookbehind before the end of the line.
And replace with a space.
$title = preg_replace('/(?<=[A-Za-z0-9?!])$/',' ', $title);
Try it here
You may want to try this Pattern Matching below to see if that does it for you.
<?php
// THE REGEX BELOW MATCHES THE ENDING LOWER & UPPER-CASED CHARACTERS, DIGITS
// AND SYMBOLS LIKE "?" AND "!" AND EVEN A DOT "."
// HOWEVER YOU CAN IMPROVISE ON YOUR OWN
$rxPattern = "#([\!\?a-zA-Z0-9\.])$#";
$title = "What is your name?";
var_dump($title);
// AND HERE, YOU APPEND A SINGLE SPACE AFTER THE MATCHED STRING
$title = preg_replace($rxPattern, "$1 ", $title);
var_dump($title);
// THE FIRST var_dump($title) PRODUCES:
// 'What is your name?' (length=18)
// AND THE SECOND var_dump($title) PRODUCES
// 'What is your name? ' (length=19) <== NOTICE THE LENGTH FROM ADDED SPACE.
You may test it out HERE.
Cheers...
You need
$title=preg_replace("/.*[\w?!]$/", "\\0 ", $title);

strreplace PHP function for utf-8 string

I want to replace character at specific index of string.
preg_replace('/('.$txt.')/u', $replacement, $str,1);
but it's not taking index, so not working for me.
How can I do this easily?
To manipulate Unicode strings, you need to use appropriate string functions. Here, you can use mb_substr:
Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
Sample PHP code:
$str = "Вася";
$replacement = "н";
$start = 3;
echo mb_substr($str,0,$start-1,"utf8") .
$replacement .
mb_substr($str,$start,mb_strlen($str),"utf8");
This will change Вася into Ваня as the 3rd symbl will get "replaced" with the $replacement.
See IDEONE demo
With php, if you do
$string[1] = $replacement;
It will replace the character within the String.

Find last character of php string

I Have one string like below.
$string = "2346#$ABSC$%###234567";
Now I want last character from this string that is not numeric or special character, It should be only A-a to Z-z.
Means, I need only "C" from this string.
I have try this formula:
substr($string, -1);
You should look into regular expressions using something like preg_match()
An expression like this would match:
/([a-z])[^a-z]*$/i
It means:
([a-z]) Capture an a-z character (the i at the end makes it case-insensitive)
[^a-z]*$ followed by 0 or more non a-z characters until the end of the string
See an example.
This should work for you:
(Here I just replace everything expect a-zA-Z with an empty string. After this I just access the last character)
<?php
$string = '2346#$ABSC$%###234567';
$string = preg_replace("/[^a-zA-Z]/", "", $string);
echo $string[strlen($string)-1];
?>
output:
C
The proper regex is: ([a-z])[^a-z]*$

Categories