Extract text regex php

PHP extract substring from strings in text

something like substr($text, $start-point, $lenght) but how to calculate the lenght of the numeric part only?

@Luke substr is also a good way to do yes, to calculate the length of the numeric part you could just read from 4 to the end of the string.

@ClémentMalet thank you, the problem is that the numeric part has a variable lenght and after the numeric part there is a space and then another string

3 Answers 3

You can use regular expression and preg_match() function

$string = "atm123456"; $pattern = "(atm\d+)"; preg_match($pattern, $string, $matches); // you may use preg_match_all() as well print_r($matches); 
 $thestring='atm123456'; $thestrToEx = explode(' ',$thestring ); $thestrToExArr=array_walk($thestrToEx,'intval'); $theValues=explode($thestrToExArr,$thestring); echo $thestrToExArr.$theValues[1]; 

in case of multiple value or repeated items. you can use preg_match_all like this

$string = "atm123456 with atm7890 items"; $pattern = "(atm\d+)"; preg_match_all($pattern, $string, $matches); print_r($matches); 

sir, I just give the option in case of preg_match_all with string example, you were just considering preg_match only.

It was already mentioned in my answer; even in my regex demo. I’m ok with that, just. weird to me man. Well, have fun 😉

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Extracting matches from php regex

How to extract the email from there? (We can explode it and get it. but would like a method to get it directly through regex)?

6 Answers 6

Try using the named subpattern syntax of preg_match:

\w+): (?\d+)/', $str, $matches); // Before PHP 5.2.2, use this: // preg_match('/(?P\w+): (?P\d+)/', $str, $matches); print_r($matches); ?> 
 Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 ) 

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags [, int $offset ]]] )

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches1 will have the text that matched the first captured parenthesized subpattern, and so on.

$subject = "E:contact@customer.com I:100955"; $pattern = "/^E:(?\w+) I:(?\d+)$/"; if (preg_match($pattern, $subject,$matches))
  1. go to regex101.com
  2. Use the great documentation for creating and testing your regex (make sure you select PHP).
  3. In the TOOLS section click on code generation
  4. This is an example of what I got.
$re = '/\#.*@hello\((?\w+),?(?.*)\).*/m'; $str = ' Testing string # @hello(group_fields) # @hello(operator, arguments, more arguments)'; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); // Print the entire match result var_dump($matches); 

Источник

PHP: Best way to extract text within parenthesis?

What’s the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string «text» from the string «ignore everything except this (text)» in the most efficient manner possible. So far, the best I’ve come up with is this:

$fullString = "ignore everything except this (text)"; $start = strpos('(', $fullString); $end = strlen($fullString) - strpos(')', $fullString); $shortString = substr($fullString, $start, $end); 

Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?

10 Answers 10

i’d just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it’s just easier to code (and understand when you look back on it)

$text = 'ignore everything except this (text)'; preg_match('#\((.*?)\)#', $text, $match); print $match[1]; 

not necessarily, ? is a lazy match. without it, a string like ‘ignore (everything) except this (text)’, the match would end up being ‘everthing) except this (text’

Good to know. Should avoid all those squared nots. E.g. /src=»https://stackoverflow.com/questions/196520/([%5E»]*)»/ now replaced with /src=»https://stackoverflow.com/questions/196520/(.*?)»/ 😀

It’s good that you can «understand when you look back on it». Failing that, you’ve got some Stack Overflow comments to clarify it.

So, actually, the code you posted doesn’t work: substr()’s parameters are $string, $start and $length, and strpos()’s parameters are $haystack , $needle . Slightly modified:

$str = "ignore everything except this (text)"; $start = strpos($str, '('); $end = strpos($str, ')', $start + 1); $length = $end - $start; $result = substr($str, $start + 1, $length - 1);

Some subtleties: I used $start + 1 in the offset parameter in order to help PHP out while doing the strpos() search on the second parenthesis; we increment $start one and reduce $length to exclude the parentheses from the match.

Also, there’s no error checking in this code: you’ll want to make sure $start and $end do not === false before performing the substr .

As for using strpos/substr versus regex; performance-wise, this code will beat a regular expression hands down. It’s a little wordier though. I eat and breathe strpos/substr , so I don’t mind this too much, but someone else may prefer the compactness of a regex.

Источник

php regex to extract data from HTML table

This I want to replace by: quote1:have you trying it off and on again ? quote65:You wouldn’t steal a helmet of a policeman the code that I already have written is this:

5 Answers 5

If you really want to use regexes (might be OK if you are really really sure your string will always be formatted like that), what about something like this, in your case :

$str =  quote1 have you trying it off and on again ?  quote65 You wouldn't steal a helmet of a policeman   A; $matches = array(); preg_match_all('#\s+?(.*?)\s+?(.*?)\s+?#', $str, $matches); var_dump($matches); 

A few words about the regex :

You then get the results you want in $matches[1] and $matches[2] (not $matches[0] ) ; here’s the output of the var_dump I used (I’ve remove entry 0, to make it shorter) :

array 0 => . 1 => array 0 => string 'quote1' (length=6) 1 => string 'quote65' (length=7) 2 => array 0 => string 'have you trying it off and on again ?' (length=37) 1 => string 'You wouldn't steal a helmet of a policeman' (length=42) 

You then just need to manipulate this array, with some strings concatenation or the like ; for instance, like this :

$num = count($matches[1]); for ($i=0 ; $i'; > 
quote1:have you trying it off and on again ? quote65:You wouldn't steal a helmet of a policeman 

Note : you should add some security checks (like preg_match_all must return true, count must be at least 1, . )

As a side note : using regex to parse HTML is generally not a really good idea ; if you can use a real parser, it should be way safer.

Источник

Extracting words from a text using php

Hello friends have a little problem. I need to extract only the words of a text «anyone». I tried to retrieve the words using strtok (), strstr (). some regular expressions, but only managed to extract some words. The problem is complex due to the number of characters and symbols that can accompany the words. The example text which must be extracted words. This is a sample text:

Main article: our 46,000 required, !but (1947-2011) mail@server.com March 8, 2014 Gutenberg's 34-DE 'a' 3,1415 Us: @unknown n go http://google.com or www.google.com and http://www.google.com (r) The 509th "composite" and; C-54 #dog v4.0 ¿as is done? ¿article. agriculture? x ¿cat? now! Hi!! (87 meters). Sample text, for testing. 
Main article our required but March Gutenberg's a go or and The composite and dog as is done article agriculture cat now Hi meters Sample text for testing 
function PreText($text)< $text = str_replace("\n", ".", $text); $text = str_replace("\r", ".", $text); $text = str_replace("'", "", $text); $text = str_replace("?", "", $text); $text = str_replace("¿", "", $text); $text = str_replace("(", "", $text); $text = str_replace(")", "", $text); $text = str_replace('"', "", $text); $text = str_replace(';', "", $text); $text = str_replace('!', "", $text); $text = str_replace('', "", $text); $text = str_replace('#', "", $text); $text = str_replace(",", "", $text); $text = str_replace(".c", "", $text); $text = str_replace(".C", "", $text); return $text; > 
function SplitWords($text) < $words = explode(" ", $text); $ContWords = count($words); for ($i = 0; $i < $ContWords; $i++)< if (ctype_alpha($words[$i])) < $NewText .= $words[$i].", "; >> return $NewText; > 

Источник

Читайте также:  Css free templates e commerce
Оцените статью