Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string between, php

Tags:

string

php

as I am new to php, and after googling :) I still could not find what I wanted to do.

I have been able to find start and end position in string that i want to extract but most of the example use strings or characters or integers to get string between but I could not find string bewteen two positions.

For example: $string = "This is a test trying to extract"; $pos1 = 9; $pos2 = 14;

Then I get lost. I need to get the text between position 9 and 14 of of the string. Thanks.

like image 265
Jackie Avatar asked Jul 12 '11 16:07

Jackie


People also ask

How can I get data between two strings in PHP?

Syntax: $arr=explode(separator, string). This will return an array which will contain the string split on the basis of the separator. Split the list on the basis of the starting word.

How do I cut a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

What is a substring in PHP?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above.

How can I get certain words from a string in PHP?

How do I find a specific word in a string? Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string.


2 Answers

$startIndex = min($pos1, $pos2);
$length = abs($pos1 - $pos2);

$between = substr($string, $startIndex, $length);
like image 124
user703016 Avatar answered Oct 14 '22 18:10

user703016


You can use substr() to extract part of a string. This works by setting the starting point and the length of what you want to extract.

So in your case this would be:

$string = substr($string,9,5); /* 5 comes from 14-9 */
like image 43
Kokos Avatar answered Oct 14 '22 18:10

Kokos