Remove left string after found specific word - PHP regular expression - php

I have a problem regarding regular expression. Let say I have a string like this:
/media/bcd44b6a-9c2e-4496-81da-b45d3c349c91/abcd/planet/document/sola
I need to remove all the string before word sola and take the string from sola onwards. Meaning, the output it will be like this:
sola/path/anotherpath/../..
So how I'm gonna do that. Please help me. Thank you in advance.

$string="/media/bcd44b6a-9c2e-4496-81da-b45d3c349c91/abcd/planet/document/sola-asda";
echo substr($string,strpos($string,"sola")+4); // -asda

use string explode
$string1 = "your string" //url
$string2 = "the part you need"; //Sola
$string3 = ""; //string with the result;
$strings = explode($string2, $string1);
$c = count($strings);
if($c < 2){
echo "not found";
}else{
$i = 1;
while($i < $c){
$string3 .= $string2.$strings[$i];
$i++;
}
}

Related

replace every other character in a string with php

In php is there a quick way of replacing every other character (non spaces) in a string with something else ? I searched around and haven't found a solution.
Take something like this:
$str = "This is my example string!"
And end up with something like this:
$result = "T*i* i* m* e*a*p*e s*r*n*!
Simple preg_replace() solution:
$str = "This is my example string!";
$result = preg_replace('/(\S)\S/', '$1*', $str);
print_r($result);
The output:
T*i* i* m* e*a*p*e s*r*n*!
\S - stands for non-whitespace character
You can treat the string as an array, loop through it and change the character using modulo to check for parity:
<?php
$string = "This is my test string";
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$string[$i] = $i % 2 === 0 ? $string[$i] : "*";
}
echo $string;
Result:
T*i* *s*m* *e*t*s*r*n*
Demo

Formatting string according to pattern without regex in php

How can I format an arbitrary string according to a flexible pattern? The only solution I came up with is using regular expressions, but then I need 2 "patterns" (one for the search and one for the output).
Example:
$str = '123ABC5678";
Desired output: 12.3AB-C5-67.8
I would like to use a pattern in a variable (one that a user can easily define without knowledge of regular expressions) It could look like this:
$pattern = '%%.%%%-%%-%%.%';
So the user would just have to use 2 different characters (% and .)
A solution with regex would look like this:
$str = '123ABC5678';
$pattern_src = '#(.{2})(.{3})(.{2})(.{2})(.{1})#';
$pattern_rpl = "$1.$2-$3-$4.$5";
$res = preg_replace($pattern_src, $pattern_rpl, $str);
//$res eq 12.3AB-C5-67.8
Way too complicated since the user would need to define $pattern_src and $pattern_rpl. If the string could vary in length, it would be even more complex to explain.
Yes, I could write a function/parser that builds the required regular expressions based on a simple user pattern like %%.%%%-%%-%%.%. But I wonder if there is any "built in" way to achieve this with php? I was thinking about sprintf etc., but that doesn't seem to do the trick. Any ideas?
I was thinking about sprintf etc., but that doesn't seem to do the trick.
You're on the right track. You can accomplish this with vsprintf as follows:
$str = '123ABC5678';
$pattern = '%%.%%%-%%-%%.%';
echo vsprintf(str_replace('%', '%s', $pattern), str_split($str));
Output:
12.3AB-C5-67.8
This is assuming the number of % characters in $pattern match the length of $str.
Why not write a simple parser that works as follows:
For each character of pattern:
if you match percent character, output next character from input
if you match any other character, output it
$str = '123ABC5678';
$pattern = '%%.%%%-%%-%%.%';
if (strlen($str) < substr_count($pattern, '%'))
Die('The length of input string is lower than number number of placeholders');
$len = strlen($pattern);
$stringIndex = 0;
$output = '';
for ($i = 0; $i < $len; $i++) {
if ($pattern[$i] === '%') {
$output .= $str[$stringIndex];
$stringIndex++;
} else {
$output .= $pattern[$i];
}
}
echo $output;
I have a similar solution that looks like this.
<?php
$format = '%%.%%%-%%-%%.%';
$string = '123ABC5678';
$new_string = '';
$c = 0;
for( $i = 0; $i < strlen( $format ); $i++ )
{
if( $format[ $i ] == '%' )
{
$new_string .= $string[ $c ];
$c++;
}
else
{
$new_string .= $format[ $i ];
}
}
echo $new_string;
Output:
12.3AB-C5-67.8
How about this pattern from the user?
2.3-2-2.1
Where the pattern is a number means n chars, a dot or dash means add a dot or dash.
Now you make a regex to parse the user input:
preg_match_all("/(.)/", $User_input, $pattern);
Now you will have an array with either numbers or dots and dashes.
So loop through the array and build the string:
$string = '123ABC5678';
$User_input = "2.3-2-2.1";
preg_match_all("/(.)/", $User_input, $pattern);
$i=0;
$str="";
foreach($pattern[1] as $val){
if(is_numeric($val)){
$str .= substr($string,$i,$val);
$i=$i+$val;
}else{
$str .= $val;
}
}
echo $str;
https://3v4l.org/5eg5G

PHP hide part of string

I'm searching for the most elegant way in PHP to hide a string (for example an username).
For example, usernames should be shown as:
tim will be shown as: t*m
So the username itself is not completely "cryptically", but no one can guess their login name or at least not for sure.
You can use preg_replace:
$string = 'usernameTest';
echo preg_replace("/(?!^).(?!$)/", "*", $string); // u**********t
(?!^) Checks if the character is not the first character in the string.
. matches any character
(?!$) Checks if the character is not the last character in the string.
Hope this helps.
You can use the following regex along with preg_replace function like as
(^.|.$)(*SKIP)(*F)|(.)
Example
$your_string = "Narendra";
echo preg_replace("/(^.|.$)(*SKIP)(*F)|(.)/","*",$your_string);
Output :
N******a
Explanation of Regex:
(^.|.$) This'll capture the first and last alphabet of the word
(*SKIP)(*F) This'll skip the above captured words
|(.) Over here rest of the alphabets'll be captured and can be replaced further with your character i.e. * over here
Demo
Try:
function get_starred($str) {
$len = strlen($str);
return substr($str, 0, 1).str_repeat('*', $len - 2).substr($str, $len - 1, 1);
}
$myStr = 'YourName';
echo get_starred($myStr); //should show Y******e
You can do something like this for example:
<?php
function HideUN($username = "") {
$replaced = "";
# Count the characters in username and remove an extra asterik (*)
# Substring, remove all characters and leave the first one and add the last one
for($i = 0; $i < strlen($username) -1; $i++) $replaced .= "*";
return substr($username, 0, 1)."".$replaced."".substr($username, -1, 1);
}
# Call this function
$string = "John";
echo HideUN($string);
?>
The substr() removes all characters after the first one, then the for() loop, counts the characters from $string and then we gonna add the asterik (*) to an other variable called $replaced.
Then at the end we put them together in an echo. Output: J***n
function Split_Hide_Name($name) {
$name = trim($name);
$split_name = explode(' ',$name);
foreach($split_name as $v) {
$string []= strlen($v);
}
$number_of_letters_to_show = 3;
$first_name_length = $string[0];
$last_name_length = $string[count($string)-1];
$first_name1 = $split_name[0];
$last_name1 = $split_name[count($string)-1];
$fname_cover = '';
for ($i = 0; $i < $first_name_length - $number_of_letters_to_show; $i++){
$fname_cover .="*";
}
$lname_cover = '';
for ($i = 0; $i < $last_name_length - $number_of_letters_to_show; $i++){
$lname_cover .="*";
}
$first_name = substr_replace($first_name1,$fname_cover,$number_of_letters_to_show);
$last_name = substr_replace($last_name1,$lname_cover,$number_of_letters_to_show);
return $first_name.' '.$last_name;}

count the occurrences of all the letters in a string PHP

I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in
string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
you can do it by following way as well:
$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

trying to cut off at the last character that's a space

I need to find out where the last character in the string is where the charachter is a space, and cut it off there. This is the function I'm using, but there seems to be something wrong with the if statement, but I can't figure out what. There is certainly a space in the $text-string.
Let's say I have a string "Hey, my name is Joh". Then it has to be shortened to "Hey, my name is ".
$checkLastChar = false;
$text = $line[2];
while($checkLastChar != true){
for($i = 1; $i <= strlen($text); $i++)
{
if($text[strlen($tekst) - $i] == " ") {
$checkLastChar = true;
$text = substr($text, 1, strlen($text) - $i);
}
}
}
substr($string, 0, strrpos($string, ' '));
Why don't you use rtrim()?
update
Based on the clarification a solution like Nate's seems to be more appropriate.
Have you ever considered using trim()? It strips the spaces from beginning AND end.
Example:
echo trim(' Hello my name is Matt. ');
Try this:
<?php
$str = "dsajhc \tsjdtgsd "; // string with whitespaces
$str = preg_replace( '/(\s+.*)/i', '', $str ); // remove everything after whitespace
?>
Hope it helps.

Categories