Jump to content

How can I match parts of a string to variables?


DWilliams

Recommended Posts

String processing and regex type things are my weakness. I think I'm looking for the opposite of sprintf. What I want to do is take an input string and assign parts of it to variables, or something similar that accomplishes the same goal.

 

For example, something like this (obviously it won't work):

 

$inputString = "Bob says to you, 'stuff' ";
$pattern = "%0 says to you, '%1' ";

magical_string_function($inputString, $pattern, $matchVar1, $matchVar2);

echo $matchVar1; // Bob
echo $matchVar2; // stuff

preg_match would be the way to do it:

 

<?php
$string = "Bob says to you 'hello'";

preg_match("~([A-Z0-9]+?) .* '([A-Z0-9]+?)'~i", $string, $matches);

print_r($matches);
?>

 

See my signature for references for Regular Expression Syntax.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.