Get first string before separator? - php

I have strings with folowing structure:
7_string_12
7_string2_122
7_string3_1223
How I can get string before second "_" ?
I want my final result to be :
7_string
7_string2
7_string3
I am using explode('_', $string) and combine first two values, but my script was very slow!

$str = '7_string_12';
echo substr($str,0,strrpos($str,'_'));
echoes
7_string
no matter what's at the begining of the string

If it always starts with 7_ you can try this:
$string = substr($text, 0, strpos($text, '_', 2));
The strpos() searches for the first _ starting from character 3 (= s from string). Then you use substr() to select the whole string starting from the first character to the character returned by strpos().

$s1 = '7_string_12';
echo substr($s1, 0, strpos($s1, '_', 2));

Related

PHP String stripped and stored

I have a long string that I want everything from the first "-" on to be removed and the remaining saved.
I have tried rtrim and this does not work. can figure explode so that will not work
Use substr() with strpos().
$str = "3568206020-1201103628-13107292-0001";
//extract the substring from start to the first occurrence of the character `-`.
$str = substr($str, 0, strpos($str, "-"));
Output - 3568206020

php regex replace each character with asterisk

I am trying to something like this.
Hiding users except for first 3 characters.
EX)
apple -> app**
google -> goo***
abc12345 ->abc*****
I am currently using php like this:
$string = "abcd1234";
$regex = '/(?<=^(.{3}))(.*)$/';
$replacement = '*';
$changed = preg_replace($regex,$replacement,$string);
echo $changed;
and the result be like:
abc*
But I want to make a replacement to every single character except for first 3 - like:
abc*****
How should I do?
Don't use regex, use substr_replace:
$var = "abcdef";
$charToKeep = 3;
echo strlen($var) > $charToKeep ? substr_replace($var, str_repeat ( '*' , strlen($var) - $charToKeep), $charToKeep) : $var;
Keep in mind that regex are good for matching patterns in string, but there is a lot of functions already designed for string manipulation.
Will output:
abc***
Try this function. You can specify how much chars should be visible and which character should be used as mask:
$string = "abcd1234";
echo hideCharacters($string, 3, "*");
function hideCharacters($string, $visibleCharactersCount, $mask)
{
if(strlen($string) < $visibleCharactersCount)
return $string;
$part = substr($string, 0, $visibleCharactersCount);
return str_pad($part, strlen($string), $mask, STR_PAD_RIGHT);
}
Output:
abc*****
Your regex matches all symbols after the first 3, thus, you replace them with a one hard-coded *.
You can use
'~(^.{3}|(?!^)\G)\K.~'
And replace with *. See the regex demo
This regex matches the first 3 characters (with ^.{3}) or the end of the previous successful match or start of the string (with (?!^)\G), and then omits the characters matched from the match value (with \K) and matches any character but a newline with ..
See IDEONE demo
$re = '~(^.{3}|(?!^)\G)\K.~';
$strs = array("aa","apple", "google", "abc12345", "asdddd");
foreach ($strs as $s) {
$result = preg_replace($re, "*", $s);
echo $result . PHP_EOL;
}
Another possible solution is to concatenate the first three characters with a string of * repeated the correct number of times:
$text = substr($string, 0, 3).str_repeat('*', max(0, strlen($string) - 3));
The usage of max() is needed to avoid str_repeat() issue a warning when it receives a negative argument. This situation happens when the length of $string is less than 3.

php pattern matching

I want to get the part of the string before the last occurance of "-",
for example,
$string1 = 'a-b-c-de-f-gfgh';
I want to get this part returned: a-b-c-de-f. Of course, I don't know the length of the last part.
What is the easy way to do it?
Thank you
echo substr ($string1, 0, strrpos ($string1, '-'));
strrpos() finds the last occurrence of a substring, - in this case, and substr() splits the original string from the 0th character until the nth character as defined by strrpos()
Use strrpos() to get position of last "-" and substr() it:
echo substr($string1, 0, strrpos($string1, "-"));
get the last occurrence of - using $x = strrpos($string1,'-');
then use substr() to return the decired string from 0 to $x
echo substr ($string1, 0, $x);
You could remove that last part:
$string = preg_replace("|-[^-]+$|", "", $string);
As an alternative to the other posters:
preg_match('/(.*)-[^-]+/', 'a-b-c-de-f-gfgh', $result);
Result:
Array
(
[0] => a-b-c-de-f-gfgh-a
[1] => a-b-c-de-f-gfgh
)
Though I like Jeroens solution more.

Delete first 3 characters and last 3 characters from String PHP

I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both first and last characters i'm not sure if I can actually use this. Any suggestions?
Pass a negative value as the length argument (the 3rd argument) to substr(), like:
$result = substr($string, 3, -3);
So this:
<?php
$string = "Sean Bright";
$string = substr($string, 3, -3);
echo $string;
?>
Outputs:
n Bri
Use
substr($var,1,-1)
this will always get first and last without having to use strlen.
Example:
<?php
$input = ",a,b,d,e,f,";
$output = substr($input, 1, -1);
echo $output;
?>
Output:
a,b,d,e,f
As stated in other answers you can use one of the following functions to reach your goal:
substr($string, 3,
-3) removes 3 chars from start and end
trim($string, ",") removes all specific chars from start and end
ltrim($string, ".") removes all specific chars from start
rtrim($string, ";") removes all specific chars from end
It depends on the amount of chars you need to remove and if the removal needs to be specific. But finally substr() answers your question perfectly.
Maybe someone thinks about removing the first/last char through string dereferencing. Forget that, it will not work as null is a char as well:
<?php
$string = 'Stackoverflow';
var_dump($string);
$string[0] = null;
var_dump($string);
$string[0] = null;
var_dump($string);
echo ord($string[0]) . PHP_EOL;
$string[1] = '';
var_dump($string);
echo ord($string[1]) . PHP_EOL;
?>
returns:
string(13) "Stackoverflow"
string(13) "tackoverflow"
string(13) "tackoverflow"
0
string(13) "ackoverflow"
0
And it is not possible to use unset($string[0]) for strings:
Fatal error: Cannot unset string offsets in /usr/www/***.php on line **
substr($string, 3, strlen($string) - 6)
I don't know php, but can't you take the length of the string, start as position 3 and take length-6 characters using substr?
$myString='123456789';
$newString=substr($myString,3,-3);

Get part of string using php

How to get a part of string using PHP?
I have a string like this.
$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';
I want only the link.. like this
$str_new = "http://www.idontknow.com/areyousure?answer=yes";
$str_new = substr($str, 6, -1);
substr()
If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned.
If length is given and is 0, FALSE or NULL an empty string will be returned.
If length is omitted, the substring starting from start until the end of the string will be returned.
$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';
preg_match('/href="(.*)"/', $str, $matches);
$str_new = $matches[1];
echo $str_new;
Output:
http://www.idontknow.com/areyousure?answer=yes
Try
$result = substr($input, 6, strlen($input) - 1);
Use a regular expression:
$str = 'href="http://www.idontknow.com/areyousure?answer=yes"';
$string = preg_replace ( '/href="(.*)"/', '\1', $str );
$str = preg_replace('/href=/i', '', $str);

Categories