Get part of string using php - 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);

Related

Remove X char from string

I need to know how to do this reliably with the least amount of calls.
I have a string and I need to remove the 8th character from it. It doesn't matter what the char is, I just need to remove ONLY the 8th char.
I came up with this but a little too unwieldy for me.
// 12345678901234567890
$str = '5NMSG3AB1AH353158';
// after removing char, result should be:
// 5NMSG3A1AH353158
$r = str_split($str);
unset($r[7]);
echo join('', $r);
Possibly Regex?
Here are some solutions:
$str = substr($str, 0, 7) . substr($str, 8);
$str = substr_replace($str, '', 7, 1);
$str = preg_replace('/(.{7})./', '$1', $str, 1);
$str = preg_replace('/.{7}\K./', '', $str, 1);
I'd go for substr() or better substr_replace() as this will certainly be fastest and most easy to read.
substr_replace makes this very simple.
$string = substr_replace($string, '', 7, 1);
It can also take an array of strings as its first parameter, and do the same replacement in all of them, which can be pretty handy.
Like this
$str = '5NMSG3AB1AH353158';
echo preg_replace('/^(.{7})./', '\1', $str);
Output:
5NMSG3A1AH353158
Sandbox
Explanation
^ start of string
(...) capture
. match any
{7} seven times
. match any one time
Then the replacement
\1 first capture group
Basically capture the first 7 chars, then match the 8th, and replace that with the captured 7 chars. Which effectively removes the 8th.
UPDATE
here is another way I like (I haven't used that function sense college, I think):
$s = '5NMSG3A1AH353158';
echo substr_replace($s,'',7,1); //strings are 0 based
sandbox
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
mixed substr_replace( mixed $string, mixed $replacement, mixed $start [, mixed $length ] )
http://php.net/manual/en/function.substr-replace.php
Simple.

Trim all characters before an integer in a string in PHP?

I have an alpha numeric string say for example,
abc123bcd , bdfnd567, dfd89ds.
I want to trim all the characters before the first appearance of any integer in the string.
My result should look like,
abc , bdfnd, dfd.
I am thinking of using substr. But not sure how to check for a string before first appearance of an integer.
You can easily remove the characters you don't want with preg_replace [docs] and a regular expression:
$str = preg_replace('#\d.*$#', '', $str);
\d matches a digit and .*$ matches any character until the end of the string.
Learn more about regular expressions: http://www.regular-expressions.info/.
DEMO
A possible non-Regex solution would be:
strcspn — Find length of initial segment not matching mask
substr — Return part of a string
Example:
$string = 'foo1bar';
echo substr($string, 0, strcspn($string, '1234567890')); // gives foo
$string = 'abc123bcd';
preg_replace("/[0-9]/", "", $string);
or
trim($string, '0123456789');
I believe you are looking for this?
$matches = array();
preg_match("/^[a-z]+/", "dfd89ds", $matches);
echo $matches[0]; // returns dfd
You can use a regex for this:
$string = 'abc123bcd';
preg_match('/^[a-zA-Z]*/i', $string, $matches);
var_dump($matches[0]);
will produce:
abc
To remove the +/- sign, you can simply use:
abs($number)
and get the absolute value.
e.g
$abs = abs($signed_integer);

Get first string before separator?

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));

how to shorten a string by certain number of characters?

Is there a php function that can chop let's say 10 chars of the end of a string without calling strlen ? So I can avoid unnecessary repeating of variable names.
all I know is substr($str,0,strlen($str)-10);
Read the manual: http://php.net/manual/en/function.substr.php.
...
If length is given and is negative, then that many characters will
be omitted from the end of string.
...
$rest = substr("abcdef", 0, -1); // returns "abcde"
The documentation for substr clearly states:
string substr ( string $string , int $start [, int $length ] )
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.
So:
$str = substr($str, 0, -10);
Please, always use the documentation as your first port of call for reference questions. There is no reason at all not to use it.
It's simple: You should also check to subtract length of the $str if the length is less that your required chars to remove.
substr($str,0,-10);
If you give it a negative length, it'll remove that many characters from the end.
substr($str, 0, -10);
http://sandbox.phpcode.eu/g/4fb74.php
-10 without strlen :)
<?php
$str = "01234567890123456789";
echo substr($str,0,-10);
outputs 0123456789

How to extract a substring from a string in PHP until it reaches a certain character?

I have part of a PHP application which assess a long string input by the user, and extracts a number which always begins 20 characters into the string the user supplies.
The only problem is that I don't know how long the number for each user will be, all I do know is the end of the number is always followed by a double quote (").
How can I use the PHP substring function to extract a substring starting form a specific point, and ending when it hits a double quote?
Thanks in advance.
You can use strpos to get the first position of " from the position 20 on:
$pos = strpos($str, '"', 20);
That position can then be used to get the substring:
if ($pos !== false) {
// " found after position 20
$substr = substr($str, 20, $pos-20-1);
}
The calculation for the third parameter is necessary as substr expects the length of the substring and not the end position. Also note that substr returns false if needle cannot be found in haystack.
$nLast = strpos($userString , '"');
substr($userString, 0, $nLast);
<?
$str = substring($input, 20, strpos($input, '"') - 20);
echo $str;
?>
Or something like that etc.
find first occurrence of double quote after 20 chars, substract 19 - that gives you length of desired substring:
$dq = strpos($string,'"',19); //19 is index of 20th char
$desired_string = substr($string,19,$dq-19);
Going to just add on to Gumbo's answer in case you need help with the substring function:
$pos = strpos($str, '"', 20);
$substring = substr($str, 20, $pos);

Categories