strreplace PHP function for utf-8 string - php

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.

Related

How can remove the numberic suffix in php?

For example, if I want to get rid of the repeating numeric suffix from the end of an expression like this:
some_text_here_1
Or like this:
some_text_here_1_5
and I want finally receive something like this:
some_text_here
What's the best and flexible solution?
$newString = preg_replace("/_?\d+$/","",$oldString);
It is using regex to match an optional underscore (_?) followed by one or more digits (\d+), but only if they are the last characters in the string ($) and replacing them with the empty string.
To capture unlimited _ numbers, just wrap the whole regex (except the $) in a capture group and put a + after it:
$newString = preg_replace("/(_?\d+)+$/","",$oldString);
If you only want to remove a numberic suffix if it is after an underscore (e.g. you want some_text_here14 to not be changed, but some_text_here_14 to be changed), then it should be:
$newString = preg_replace("/(_\d+)+$/","",$oldString);
Updated to fix more than one suffix
Strrpos is far better than regex on such a simple string problem.
$str = "some_text_here_13_15";
While(is_numeric(substr($str, strrpos($str, "_")+1))){
$str = substr($str,0 , strrpos($str, "_"));
}
Echo $str;
Strrpos finds the last "_" in str and if it's numeric remove it.
https://3v4l.org/OTdb9
Just to give you an idea of what I mean with regex not being a good solution on this here is the performance.
Regex:
https://3v4l.org/Tu8o2/perf#output
0.027 seconds for 100 runs.
My code with added numeric check:
https://3v4l.org/dkAqA/perf#output
0.003 seconds for 100 runs.
This new code performs even better than before oddly enough, regex is very slow. Trust me on that
You be the judge on what is best.
First you'll want to do a preg_replace() in order to remove all digits by using the regex /\d+/. Then you'll also want to trim any underscores from the right using rtrim(), providing _ as the second parameter.
I've combined the two in the following example:
$string = "some_text_here_1";
echo rtrim(preg_replace('/\d+/', '', $string), '_'); // some_text_here
I've also created an example of this at 3v4l here.
Hope this helps! :)
$reg = '#_\d+$#';
$replace = '';
echo preg_replace($reg, $replace, $string);
This would do
abc_def_ghi_123 > abc_def_ghi
abc_def_1 > abc_def
abc_def_ghi > abc_def_ghi
abd_def_ > abc_def_
abc_123_def > abd_123_def
in case of abd_def_123_345 > abc_def
one could change the line
$reg = '#(?:_\d+)+$#';

PHP str_replace can't give me the output I want

I want to replace a string at a particular position. For that I used str_replace() PHP function, but after that, I can't get an output. Here I show you what I want.
$str = "hello 8-7-2015 world -12";
// here I want replace - with ' desh ' but in date only. That I have detected using check before character if space than it should be 'minus' otherwise it should be 'desh'.
$key = strpos($str, "-");
if($key !== false){
$a = substr($str, $key-1 , 1);
if($a != " "){
$str = str_replace("-","desh",$str);
}else{
$str = str_replace("-","minus",$str);
}
}
I get output like: hello 8 desh 7 desh 2015 world desh 12 . Everywhere there is desh I want minus 12. Other values are okay and should not be changed.
Means particular position change.
Your code (with an if) doesn't loop over the string looking for all occurrences, so that should have raised an alert flag with you when all the occurrences were changed.
What it does is to find the first occurrence, which isn't preceded by a space, then it executes:
str_replace("-","desh",$str);
which replaces all occurrences within the string. In order to do what you want, all you need is:
str_replace(" -"," minus",$str);
str_replace("-","desh",$str);
This will first take care of all - character preceded by a space, turning them into " minus".
The second line will then take care of all the remaining - characters, replacing them with "desh".
Just as an aside, if you're doing this to be able to "speak" the words (in the sense of a text-to-speech (TTS) program), you probably want spaces on either sides of the words you're adding. You can achieve that with a very small modification:
str_replace(" -"," minus ",$str);
str_replace("-"," desh ",$str);
That may make it easier for your TTS code to handle the words.
There's no point in your condition since str_replace takes effect on whole the string without any relation to your $key variable.
$str = str_replace(" -","minus",$str);
$str = str_replace("-","desh",$str);
Truth is that you don't even need that condition. Simply use the first str_replace when the search term has blank space prior to it and the second str_replce doesn't. (order it's important).
You can use regex:
$str = preg_replace(
['/(\d{1,2})-(\d{1,2})-(\d{2,4})/','/-(\d+)/'],
['$1 desh $2 desh $3', 'minus $1'],
$str);
check this,
First you have to get the date from the string, then change the date format as you want after that concatenate with other strings
$str = explode(' ',$str);
$str1 = str_replace("-","desh",$str[1]);
$str2 = str_replace("-","minus",$str[2]);
$str = $str[0].$str1.$str2;

unexpected output of ltrim in 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.

Cut string from end to specific char in php

I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));

Get integer value from malformed query string

I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.
I am parsing a web page and need to grab a numeric value from the string, the string is like this
producturl.php?id=736375493?=tm
I need to be able to obtain this part of the string:
736375493
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
php.net/preg-match
<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.
Code (Demo)
$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
Output:
736375493
For completeness, there 8s another way to scan the formatted string and explicitly return an int-typed value. (Demo)
var_dump(
sscanf($str, '%*[^?]?id=%d')[0]
);
The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring. The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers. The returned value will be cast as an integer because of the %d placeholder.

Categories